Repository navigation
Expand file tree
/
Copy pathtest_utils.py
More file actions
551 lines (457 loc) · 19.8 KB
/
Copy pathtest_utils.py
File metadata and controls
551 lines (457 loc) · 19.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
"""
Tests for feast.utils module.
These unit tests cover the _populate_response_from_feature_data function
which converts raw online_read rows into protobuf FeatureVectors and
populates the GetOnlineFeaturesResponse.
"""
import http.client
import socket
import threading
import time
from datetime import datetime, timezone
from unittest.mock import MagicMock, patch
import pytest
from feast.protos.feast.serving.ServingService_pb2 import (
FieldStatus,
GetOnlineFeaturesResponse,
)
from feast.protos.feast.types.Value_pb2 import Value as ValueProto
from feast.utils import _make_dual_stack_socket, _populate_response_from_feature_data
def _can_bind_ipv6_loopback() -> bool:
"""Independent of `_ipv6_available` so a mutant in that function can't
also disable this skip guard and hide a killed mutant as a skip."""
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
sock.bind(("::1", 0))
return True
except OSError:
return False
def _make_table(name="test_fv"):
"""Create a minimal mock FeatureView for testing."""
table = MagicMock()
table.projection.name_to_use.return_value = name
table.projection.name_alias = None
table.projection.name = name
return table
class TestPopulateResponseFromFeatureData:
"""Tests for _populate_response_from_feature_data function."""
def test_basic_single_feature(self):
"""Test basic conversion with single feature and single entity."""
timestamp = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
value = ValueProto(float_val=1.5)
read_rows = [(timestamp, {"feature_1": value})]
indexes = ([0],)
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=1,
)
assert len(response.results) == 1
assert response.results[0].values[0] == value
assert response.results[0].statuses[0] == FieldStatus.PRESENT
assert response.results[0].event_timestamps[0].seconds == int(
timestamp.timestamp()
)
assert list(response.metadata.feature_names.val) == ["feature_1"]
def test_multiple_features_same_entity(self):
"""Test multiple features from the same row."""
timestamp = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
v1 = ValueProto(float_val=1.0)
v2 = ValueProto(float_val=2.0)
read_rows = [(timestamp, {"feature_1": v1, "feature_2": v2})]
indexes = ([0],)
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1", "feature_2"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=1,
)
assert len(response.results) == 2
assert response.results[0].values[0] == v1
assert response.results[1].values[0] == v2
ts1 = response.results[0].event_timestamps[0].seconds
ts2 = response.results[1].event_timestamps[0].seconds
assert ts1 == ts2 == int(timestamp.timestamp())
def test_multiple_entities_deduplication(self):
"""Test that duplicate entity rows are correctly mapped via indexes."""
ts = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
val = ValueProto(float_val=42.0)
read_rows = [(ts, {"feature_1": val})]
indexes = ([0, 1, 2],) # One unique row maps to 3 output positions
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=3,
)
assert len(response.results[0].values) == 3
for i in range(3):
assert response.results[0].values[i] == val
assert response.results[0].statuses[i] == FieldStatus.PRESENT
def test_null_timestamp_handling(self):
"""Test that null timestamps produce empty Timestamp proto."""
read_rows = [
(None, {"feature_1": ValueProto(float_val=1.0)}),
(
datetime(2024, 1, 1, tzinfo=timezone.utc),
{"feature_1": ValueProto(float_val=2.0)},
),
]
indexes = ([0],), ([1],)
indexes = ([0], [1])
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=2,
)
ts_list = response.results[0].event_timestamps
assert ts_list[0].seconds == 0 # Null timestamp -> empty proto
assert ts_list[1].seconds != 0 # Valid timestamp
def test_missing_feature_data(self):
"""Test handling of missing feature data (None row)."""
ts = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
read_rows = [
(ts, {"feature_1": ValueProto(float_val=1.0)}),
(ts, None),
]
indexes = ([0], [1])
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=2,
)
assert response.results[0].statuses[0] == FieldStatus.PRESENT
assert response.results[0].statuses[1] == FieldStatus.NOT_FOUND
def test_feature_not_in_row(self):
"""Test handling when requested feature is not in the row's data."""
ts = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
read_rows = [(ts, {"feature_1": ValueProto(float_val=1.0)})]
indexes = ([0],)
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1", "feature_2"],
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=1,
)
assert len(response.results) == 2
assert response.results[0].statuses[0] == FieldStatus.PRESENT
assert response.results[1].statuses[0] == FieldStatus.NOT_FOUND
def test_empty_inputs(self):
"""Test handling of empty inputs."""
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=[],
indexes=(),
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=0,
)
assert len(response.results) == 1
assert len(response.results[0].values) == 0
response2 = GetOnlineFeaturesResponse(results=[])
ts = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
_populate_response_from_feature_data(
requested_features=[],
read_rows=[(ts, {"f": ValueProto()})],
indexes=([0],),
online_features_response=response2,
full_feature_names=False,
table=_make_table(),
output_len=1,
)
assert len(response2.results) == 0
def test_full_feature_names(self):
"""Test that full_feature_names prefixes feature names with table name."""
ts = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
read_rows = [(ts, {"feature_1": ValueProto(float_val=1.0)})]
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=["feature_1"],
read_rows=read_rows,
indexes=([0],),
online_features_response=response,
full_feature_names=True,
table=_make_table("my_fv"),
output_len=1,
)
assert list(response.metadata.feature_names.val) == ["my_fv__feature_1"]
def test_large_scale_correctness(self):
"""Test correctness with large number of features and entities.
This test verifies that the fused implementation produces correct
results at scale (50 features x 500 entities = 25,000 data points).
"""
timestamp = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
num_entities = 500
num_features = 50
feature_data = {
f"feature_{i}": ValueProto(float_val=float(i)) for i in range(num_features)
}
read_rows = [(timestamp, feature_data.copy()) for _ in range(num_entities)]
requested_features = [f"feature_{i}" for i in range(num_features)]
indexes = tuple([i] for i in range(num_entities))
response = GetOnlineFeaturesResponse(results=[])
_populate_response_from_feature_data(
requested_features=requested_features,
read_rows=read_rows,
indexes=indexes,
online_features_response=response,
full_feature_names=False,
table=_make_table(),
output_len=num_entities,
)
assert len(response.results) == num_features
expected_ts = int(timestamp.timestamp())
for feature_idx in range(num_features):
fv = response.results[feature_idx]
assert len(fv.values) == num_entities
assert len(fv.statuses) == num_entities
assert len(fv.event_timestamps) == num_entities
for ts in fv.event_timestamps:
assert ts.seconds == expected_ts
for status in fv.statuses:
assert status == FieldStatus.PRESENT
class TestGetFeatureViewsToUseSharedSource:
def _build_store(self, data_dir):
import os
from datetime import timedelta
import pandas as pd
from feast import Entity, FeatureStore, FeatureView, Field, FileSource
from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig
from feast.on_demand_feature_view import on_demand_feature_view
from feast.repo_config import RepoConfig
from feast.types import Float64
driver = Entity(name="driver", join_keys=["driver_id"])
df = pd.DataFrame(
{
"driver_id": [1001, 1002],
"event_timestamp": [
datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
],
"created": [
datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
],
"a": [1.0, 2.0],
"b": [10.0, 20.0],
}
)
src_path = os.path.join(data_dir, "src.parquet")
df.to_parquet(path=src_path, allow_truncated_timestamps=True)
src = FileSource(
name="src_source",
path=src_path,
timestamp_field="event_timestamp",
created_timestamp_column="created",
)
src_fv = FeatureView(
name="src_fv",
entities=[driver],
ttl=timedelta(days=0),
schema=[
Field(name="a", dtype=Float64),
Field(name="b", dtype=Float64),
],
online=True,
source=src,
)
@on_demand_feature_view(
sources=[src_fv[["a"]]],
schema=[Field(name="a_out", dtype=Float64)],
mode="pandas",
)
def odfv_a(inputs):
return pd.DataFrame({"a_out": inputs["a"] + 1})
@on_demand_feature_view(
sources=[src_fv[["b"]]],
schema=[Field(name="b_out", dtype=Float64)],
mode="pandas",
)
def odfv_b(inputs):
return pd.DataFrame({"b_out": inputs["b"] + 100})
store = FeatureStore(
config=RepoConfig(
project="test_shared_source",
registry=os.path.join(data_dir, "registry.db"),
provider="local",
entity_key_serialization_version=3,
online_store=SqliteOnlineStoreConfig(
path=os.path.join(data_dir, "online.db")
),
)
)
store.apply([driver, src, src_fv, odfv_a, odfv_b])
return store
def test_shared_source_projections_are_merged(self):
import tempfile
from feast.utils import _get_feature_views_to_use
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as data_dir:
store = self._build_store(data_dir)
fvs, odfvs = _get_feature_views_to_use(
store.registry,
store.project,
["odfv_a:a_out", "odfv_b:b_out"],
)
src_entries = [fv for fv in fvs if fv.projection.name_to_use() == "src_fv"]
assert len(src_entries) == 1
projected = sorted(
feature.name for feature in src_entries[0].projection.features
)
assert projected == ["a", "b"]
assert {odfv.name for odfv in odfvs} == {"odfv_a", "odfv_b"}
def test_regular_fv_and_odfv_source_are_merged(self):
# Regression: a regular FeatureView requested alongside an ODFV that
# sources it must resolve to a single, merged src_fv entry. Previously
# the regular FV was appended but not indexed in fvs_by_projection_key,
# so the ODFV source appended a second partial src_fv projection and a
# later lookup raised "KeyError: Feature a not found in projection
# src_fv".
import tempfile
from feast.utils import _get_feature_views_to_use
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as data_dir:
store = self._build_store(data_dir)
fvs, odfvs = _get_feature_views_to_use(
store.registry,
store.project,
["src_fv:a", "odfv_b:b_out"],
)
src_entries = [fv for fv in fvs if fv.projection.name_to_use() == "src_fv"]
assert len(src_entries) == 1
projected = sorted(
feature.name for feature in src_entries[0].projection.features
)
assert projected == ["a", "b"]
assert {odfv.name for odfv in odfvs} == {"odfv_b"}
def test_regular_fv_and_odfv_source_merge_order_independent(self):
import tempfile
from feast.utils import _get_feature_views_to_use
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as data_dir:
store = self._build_store(data_dir)
fvs, _ = _get_feature_views_to_use(
store.registry,
store.project,
["odfv_b:b_out", "src_fv:a"],
)
src_entries = [fv for fv in fvs if fv.projection.name_to_use() == "src_fv"]
assert len(src_entries) == 1
projected = sorted(
feature.name for feature in src_entries[0].projection.features
)
assert projected == ["a", "b"]
def test_shared_source_ref_order_independent(self):
import tempfile
from feast.utils import _get_feature_views_to_use
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as data_dir:
store = self._build_store(data_dir)
fvs, _ = _get_feature_views_to_use(
store.registry,
store.project,
["odfv_b:b_out", "odfv_a:a_out"],
)
src_entries = [fv for fv in fvs if fv.projection.name_to_use() == "src_fv"]
assert len(src_entries) == 1
projected = sorted(
feature.name for feature in src_entries[0].projection.features
)
assert projected == ["a", "b"]
def test_make_dual_stack_socket_binds_dual_stack_when_ipv6_available():
mock_sock = MagicMock()
with patch("feast.utils._ipv6_available", return_value=True):
with patch("socket.socket", return_value=mock_sock) as mock_socket_cls:
result = _make_dual_stack_socket(6580)
mock_socket_cls.assert_called_once_with(socket.AF_INET6, socket.SOCK_STREAM)
mock_sock.setsockopt.assert_any_call(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
mock_sock.setsockopt.assert_any_call(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mock_sock.bind.assert_called_once_with(("::", 6580))
mock_sock.listen.assert_called_once_with(socket.SOMAXCONN)
mock_sock.setblocking.assert_called_once_with(False)
assert result is mock_sock
def test_make_dual_stack_socket_falls_back_to_ipv4():
mock_sock = MagicMock()
with patch("feast.utils._ipv6_available", return_value=False):
with patch("socket.socket", return_value=mock_sock) as mock_socket_cls:
_make_dual_stack_socket(6580)
mock_socket_cls.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
mock_sock.bind.assert_called_once_with(("0.0.0.0", 6580))
def test_make_dual_stack_socket_blocking_true_is_passed_through():
mock_sock = MagicMock()
with patch("feast.utils._ipv6_available", return_value=True):
with patch("socket.socket", return_value=mock_sock):
_make_dual_stack_socket(6580, blocking=True)
mock_sock.setblocking.assert_called_once_with(True)
@pytest.mark.parametrize("ipv6_available", [True, False])
def test_make_dual_stack_socket_closes_on_bind_failure(ipv6_available):
mock_sock = MagicMock()
mock_sock.bind.side_effect = OSError("address in use")
with patch("feast.utils._ipv6_available", return_value=ipv6_available):
with patch("socket.socket", return_value=mock_sock):
with pytest.raises(OSError):
_make_dual_stack_socket(6580)
mock_sock.close.assert_called_once()
def test_make_dual_stack_socket_is_reachable_on_both_families():
# Regression test: a framework's own host="::" (uvicorn.run,
# asyncio.loop.create_server) binds IPv6-only, because IPV6_V6ONLY=1
# gets set on any socket it creates itself from a host string.
# _make_dual_stack_socket must hand back a pre-bound, dual-stack socket
# instead -- this exercises the one real socket every dual-stack
# consumer (REST registry, ui, lineage) shares.
if not _can_bind_ipv6_loopback():
pytest.skip("no IPv6 loopback on this host")
import uvicorn
from fastapi import FastAPI
sock = _make_dual_stack_socket(0)
port = sock.getsockname()[1]
app = FastAPI()
@app.get("/health")
def health():
return {"ok": True}
server = uvicorn.Server(uvicorn.Config(app, log_level="critical"))
thread = threading.Thread(target=server.run, kwargs={"sockets": [sock]})
thread.daemon = True
thread.start()
try:
for _ in range(200):
if server.started:
break
time.sleep(0.01)
assert server.started, "uvicorn server did not start in time"
for host in ("127.0.0.1", "::1"):
conn = http.client.HTTPConnection(host, port, timeout=5)
try:
conn.request("GET", "/health")
resp = conn.getresponse()
assert resp.status == 200
finally:
conn.close()
finally:
server.should_exit = True
thread.join(timeout=5)