FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
feast/sdk/python/feast/feature_server.py at master · feast-dev/feast · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
feast-dev
/
feast
Public
Notifications
You must be signed in to change notification settings
Fork
1.4k
Star
7.2k
Code
Issues
218
Pull requests
191
Discussions
Actions
Security and quality
1
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Security and quality
Insights
Expand file tree
Breadcrumbs
feast
/
sdk
/
python
/
feast
/
feature_server.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1528 lines (1327 loc) · 55.6 KB
Breadcrumbs
feast
/
sdk
/
python
/
feast
/
feature_server.py
Copy path
File metadata and controls
1528 lines (1327 loc) · 55.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# Copyright 2025 The Feast Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import
asyncio
import
functools
import
os
import
sys
import
threading
import
time
import
traceback
from
collections
import
defaultdict
from
concurrent
.
futures
import
ThreadPoolExecutor
from
contextlib
import
asynccontextmanager
from
datetime
import
datetime
from
importlib
import
resources
as
importlib_resources
from
types
import
SimpleNamespace
from
typing
import
Any
,
DefaultDict
,
Dict
,
List
,
NamedTuple
,
Optional
,
Set
,
Union
import
pandas
as
pd
from
dateutil
import
parser
from
fastapi
import
(
Depends
,
FastAPI
,
Query
,
Request
,
Response
,
WebSocket
,
WebSocketDisconnect
,
status
,
)
from
fastapi
.
concurrency
import
run_in_threadpool
from
fastapi
.
logger
import
logger
from
fastapi
.
responses
import
JSONResponse
from
fastapi
.
staticfiles
import
StaticFiles
from
pydantic
import
BaseModel
,
Field
,
field_validator
import
feast
from
feast
import
metrics
as
feast_metrics
from
feast
import
proto_json
,
utils
from
feast
.
constants
import
DEFAULT_FEATURE_SERVER_REGISTRY_TTL
from
feast
.
data_source
import
PushMode
from
feast
.
errors
import
(
FeastError
,
FeatureViewNotFoundException
,
)
from
feast
.
feast_object
import
FeastObject
from
feast
.
feature_server_utils
import
convert_response_to_dict
from
feast
.
feature_view
import
FeatureViewState
from
feast
.
feature_view_utils
import
get_feature_view_from_feature_store
from
feast
.
filter_models
import
ComparisonFilter
,
CompoundFilter
from
feast
.
permissions
.
action
import
WRITE
,
AuthzedAction
from
feast
.
permissions
.
security_manager
import
(
assert_permissions
,
get_security_manager
,
is_auth_necessary
,
)
from
feast
.
permissions
.
server
.
rest
import
inject_user_details
from
feast
.
permissions
.
server
.
utils
import
(
ServerType
,
init_auth_manager
,
init_security_manager
,
str_to_auth_manager_type
,
)
from
feast
.
vector_store_utils
import
VectorStoreRegistry
,
build_vector_store_object
# TODO: deprecate this in favor of push features
class
WriteToFeatureStoreRequest
(
BaseModel
):
feature_view_name
:
str
df
:
dict
allow_registry_cache
:
bool
=
True
transform_on_write
:
bool
=
True
class
PushFeaturesRequest
(
BaseModel
):
push_source_name
:
str
df
:
dict
allow_registry_cache
:
bool
=
True
to
:
str
=
"online"
transform_on_write
:
bool
=
True
class
MaterializeRequest
(
BaseModel
):
start_ts
:
Optional
[
str
]
=
None
end_ts
:
Optional
[
str
]
=
None
feature_views
:
Optional
[
List
[
str
]]
=
None
disable_event_timestamp
:
bool
=
False
full_feature_names
:
bool
=
False
version
:
Optional
[
str
]
=
Field
(
None
,
description
=
(
"Optional version to materialize (e.g. 'v2'). Requires feature_views "
"with exactly one entry and registry.enable_online_feature_view_versioning."
),
)
class
MaterializeIncrementalRequest
(
BaseModel
):
end_ts
:
str
feature_views
:
Optional
[
List
[
str
]]
=
None
full_feature_names
:
bool
=
False
version
:
Optional
[
str
]
=
Field
(
None
,
description
=
(
"Optional version to materialize (e.g. 'v2'). Requires feature_views "
"with exactly one entry and registry.enable_online_feature_view_versioning."
),
)
class
GetOnlineFeaturesRequest
(
BaseModel
):
entities
:
Dict
[
str
,
List
[
Any
]]
feature_service
:
Optional
[
str
]
=
None
features
:
List
[
str
]
=
[]
full_feature_names
:
bool
=
False
include_feature_view_version_metadata
:
bool
=
False
class
GetOnlineDocumentsRequest
(
BaseModel
):
feature_service
:
Optional
[
str
]
=
None
features
:
List
[
str
]
=
[]
full_feature_names
:
bool
=
False
include_feature_view_version_metadata
:
bool
=
False
top_k
:
Optional
[
int
]
=
None
query
:
Optional
[
List
[
float
]]
=
None
query_string
:
Optional
[
str
]
=
None
distance_metric
:
Optional
[
str
]
=
None
api_version
:
Optional
[
int
]
=
1
filters
:
Optional
[
Union
[
ComparisonFilter
,
CompoundFilter
]]
=
None
class
OpenAISearchMetadata
(
BaseModel
):
features_to_retrieve
:
Optional
[
List
[
str
]]
=
None
content_field
:
Optional
[
str
]
=
None
class
OpenAIRankingOptions
(
BaseModel
):
ranker
:
Optional
[
str
]
=
None
score_threshold
:
Optional
[
float
]
=
None
class
OpenAISearchRequest
(
BaseModel
):
query
:
Union
[
str
,
List
[
str
]]
filters
:
Optional
[
Union
[
ComparisonFilter
,
CompoundFilter
]]
=
None
max_num_results
:
Optional
[
int
]
=
10
ranking_options
:
Optional
[
OpenAIRankingOptions
]
=
None
rewrite_query
:
Optional
[
bool
]
=
None
metadata
:
Optional
[
OpenAISearchMetadata
]
=
None
class
OpenAIVectorStoreObject
(
BaseModel
):
id
:
str
object
:
str
=
"vector_store"
name
:
str
status
:
str
=
"completed"
created_at
:
int
=
0
class
FeatureVectorResponse
(
BaseModel
):
values
:
List
[
Any
]
=
[]
statuses
:
List
[
str
]
=
[]
event_timestamps
:
List
[
str
]
=
[]
class
OnlineFeaturesMetadataResponse
(
BaseModel
):
feature_names
:
List
[
str
]
=
[]
@
field_validator
(
"feature_names"
,
mode
=
"before"
)
@
classmethod
def
_unwrap_feature_list
(
cls
,
v
:
Any
)
->
Any
:
"""Accept both the proto_json-patched flat list and the raw
protobuf ``{"val": [...]}`` dict produced by ``MessageToDict``
when the monkey-patch is absent or ineffective."""
if
isinstance
(
v
,
dict
)
and
"val"
in
v
:
return
v
[
"val"
]
return
v
class
OnlineFeaturesResponse
(
BaseModel
):
metadata
:
Optional
[
OnlineFeaturesMetadataResponse
]
=
None
results
:
List
[
FeatureVectorResponse
]
=
[]
status
:
Optional
[
bool
]
=
None
class
ChatMessage
(
BaseModel
):
role
:
str
content
:
str
class
ChatRequest
(
BaseModel
):
messages
:
List
[
ChatMessage
]
def
_parse_feature_info
(
features
:
Union
[
List
[
str
],
"feast.FeatureService"
],
)
->
tuple
:
"""Return ``(feature_view_names, feature_count)`` from resolved features.
``features`` is either a list of ``"feature_view:feature"`` strings or
a ``FeatureService`` with ``feature_view_projections``.
Returns:
(fv_names, feat_count) where fv_names is a list of unique feature
view name strings and feat_count is the total number of features.
"""
from
feast
.
feature_service
import
FeatureService
from
feast
.
utils
import
_parse_feature_ref
if
isinstance
(
features
,
FeatureService
):
projections
=
features
.
feature_view_projections
fv_names
=
[
p
.
name
for
p
in
projections
]
feat_count
=
sum
(
len
(
p
.
features
)
for
p
in
projections
)
elif
isinstance
(
features
,
list
):
feat_count
=
len
(
features
)
fv_names
=
list
({
_parse_feature_ref
(
ref
)[
0
]
for
ref
in
features
if
":"
in
ref
})
else
:
fv_names
=
[]
feat_count
=
0
return
fv_names
,
feat_count
def
_resolve_feature_counts
(
features
:
Union
[
List
[
str
],
"feast.FeatureService"
],
)
->
tuple
:
"""Return ``(feature_count_str, feature_view_count_str)`` for Prometheus labels."""
fv_names
,
feat_count
=
_parse_feature_info
(
features
)
return
str
(
feat_count
),
str
(
len
(
fv_names
))
def
_emit_online_audit
(
request
:
GetOnlineFeaturesRequest
,
features
:
Union
[
List
[
str
],
"feast.FeatureService"
],
entity_count
:
int
,
status
:
str
,
latency_ms
:
float
,
):
"""Best-effort audit log emission for online feature requests."""
try
:
from
feast
.
permissions
.
security_manager
import
get_security_manager
requestor_id
=
"anonymous"
sm
=
get_security_manager
()
if
sm
and
sm
.
current_user
:
requestor_id
=
sm
.
current_user
.
username
or
"anonymous"
fv_names
,
feat_count
=
_parse_feature_info
(
features
)
feast_metrics
.
emit_online_audit_log
(
requestor_id
=
requestor_id
,
entity_keys
=
list
(
request
.
entities
.
keys
()),
entity_count
=
entity_count
,
feature_views
=
fv_names
,
feature_count
=
feat_count
,
status
=
status
,
latency_ms
=
latency_ms
,
)
except
Exception
:
logger
.
warning
(
"Failed to emit online audit log"
,
exc_info
=
True
)
async
def
_get_features
(
request
:
Union
[
GetOnlineFeaturesRequest
,
GetOnlineDocumentsRequest
],
store
:
"feast.FeatureStore"
,
):
if
request
.
feature_service
:
feature_service
=
await
run_in_threadpool
(
store
.
get_feature_service
,
request
.
feature_service
,
allow_cache
=
True
)
assert_permissions
(
resource
=
feature_service
,
actions
=
[
AuthzedAction
.
READ_ONLINE
]
)
features
=
feature_service
# type: ignore
elif
is_auth_necessary
(
get_security_manager
()):
all_feature_views
,
all_on_demand_feature_views
=
await
run_in_threadpool
(
utils
.
_get_feature_views_to_use
,
store
.
registry
,
store
.
project
,
request
.
features
,
allow_cache
=
True
,
hide_dummy_entity
=
False
,
)
for
feature_view
in
all_feature_views
:
assert_permissions
(
resource
=
feature_view
,
actions
=
[
AuthzedAction
.
READ_ONLINE
]
)
for
od_feature_view
in
all_on_demand_feature_views
:
assert_permissions
(
resource
=
od_feature_view
,
actions
=
[
AuthzedAction
.
READ_ONLINE
]
)
features
=
request
.
features
# type: ignore
else
:
features
=
request
.
features
# type: ignore
return
features
async
def
load_static_artifacts
(
app
:
FastAPI
,
store
):
"""
Load static artifacts (models, lookup tables, etc.) into app.state.
This function can be extended to load various types of static artifacts:
- Small ML models (scikit-learn, small neural networks)
- Lookup tables and reference data
- Configuration parameters
- Pre-computed embeddings
Note: Not recommended for large language models - use dedicated
model serving solutions (vLLM, TGI, etc.) for those.
"""
try
:
# Import here to avoid loading heavy dependencies unless needed
import
importlib
.
util
import
inspect
from
pathlib
import
Path
# Look for static artifacts loading in the feature repository
# This allows templates and users to define their own artifact loading
repo_path
=
Path
(
store
.
repo_path
)
if
store
.
repo_path
else
Path
.
cwd
()
artifacts_file
=
repo_path
/
"static_artifacts.py"
if
artifacts_file
.
exists
():
# Load and execute custom static artifacts loading
spec
=
importlib
.
util
.
spec_from_file_location
(
"static_artifacts"
,
artifacts_file
)
if
spec
and
spec
.
loader
:
artifacts_module
=
importlib
.
util
.
module_from_spec
(
spec
)
spec
.
loader
.
exec_module
(
artifacts_module
)
# Look for load_artifacts function
if
hasattr
(
artifacts_module
,
"load_artifacts"
):
load_func
=
artifacts_module
.
load_artifacts
if
inspect
.
iscoroutinefunction
(
load_func
):
await
load_func
(
app
)
else
:
load_func
(
app
)
logger
.
info
(
"Loaded static artifacts from static_artifacts.py"
)
except
Exception
as
e
:
# Non-fatal error - feature server should still start
logger
.
warning
(
f"Failed to load static artifacts:
{
e
}
"
)
def
_authorize_materialize_views
(
store
:
"feast.FeatureStore"
,
feature_view_names
:
Optional
[
List
[
str
]],
version
:
Optional
[
str
]
=
None
,
)
->
List
[
str
]:
"""Resolve + authorize feature views for materialization.
Returns the resolved list of FV names (all eligible FVs when
feature_view_names is None).
"""
parsed_version
=
store
.
_validate_materialize_version
(
version
,
feature_view_names
)
feature_views_to_materialize
=
store
.
_get_feature_views_to_materialize
(
feature_view_names
,
version
=
parsed_version
)
for
fv
in
feature_views_to_materialize
:
assert_permissions
(
resource
=
fv
,
actions
=
[
AuthzedAction
.
WRITE_ONLINE
],
)
return
[
fv
.
name
for
fv
in
feature_views_to_materialize
]
def
_check_already_materializing
(
store
:
"feast.FeatureStore"
,
fv_names
:
List
[
str
],
)
->
Optional
[
JSONResponse
]:
"""Return a 409 JSONResponse if any requested FV is already MATERIALIZING."""
conflicting
:
List
[
str
]
=
[]
for
fv_name
in
fv_names
:
try
:
fv
=
store
.
registry
.
get_feature_view
(
fv_name
,
store
.
project
,
allow_cache
=
False
)
if
getattr
(
fv
,
"state"
,
None
)
==
FeatureViewState
.
MATERIALIZING
:
conflicting
.
append
(
fv_name
)
except
(
FeatureViewNotFoundException
,
KeyError
):
pass
except
Exception
as
e
:
logger
.
warning
(
f"Unexpected error checking MATERIALIZING state for
{
fv_name
}
:
{
e
}
"
)
if
conflicting
:
return
JSONResponse
(
status_code
=
409
,
content
=
{
"error"
: (
f"Cannot start async materialization — the following feature "
f"views are already in MATERIALIZING state:
{
conflicting
}
. "
f"Use ?force=true to override."
),
"feature_views"
:
conflicting
,
},
)
return
None
def
_update_fv_state
(
store
:
"feast.FeatureStore"
,
fv_names
:
List
[
str
],
state
:
FeatureViewState
,
)
->
None
:
"""Set FV state in the registry for each named feature view."""
for
fv_name
in
fv_names
:
try
:
fv
=
store
.
registry
.
get_feature_view
(
fv_name
,
store
.
project
,
allow_cache
=
False
)
fv
.
state
=
state
store
.
registry
.
apply_feature_view
(
fv
,
store
.
project
)
except
(
FeatureViewNotFoundException
,
KeyError
):
logger
.
warning
(
f"Feature view
{
fv_name
}
not found; skip state=
{
state
}
"
)
except
Exception
as
e
:
logger
.
warning
(
f"Failed to set state=
{
state
}
for
{
fv_name
}
:
{
e
}
"
)
def
_reset_stuck_materializing_to_generated
(
store
:
"feast.FeatureStore"
,
fv_names
:
List
[
str
],
)
->
None
:
"""Reset FVs currently in MATERIALIZING to GENERATED (force override)."""
stuck
:
List
[
str
]
=
[]
for
fv_name
in
fv_names
:
try
:
fv
=
store
.
registry
.
get_feature_view
(
fv_name
,
store
.
project
,
allow_cache
=
False
)
if
getattr
(
fv
,
"state"
,
None
)
==
FeatureViewState
.
MATERIALIZING
:
stuck
.
append
(
fv_name
)
except
(
FeatureViewNotFoundException
,
KeyError
):
pass
except
Exception
as
e
:
logger
.
warning
(
f"Unexpected error while force-resetting
{
fv_name
}
:
{
e
}
"
)
if
stuck
:
_update_fv_state
(
store
,
stuck
,
FeatureViewState
.
GENERATED
)
logger
.
info
(
"Force reset MATERIALIZING → GENERATED for feature views: %s"
,
stuck
)
def
_parse_materialize_timestamps
(
request
:
"MaterializeRequest"
,
)
->
tuple
:
"""Parse and validate start/end timestamps from a MaterializeRequest."""
if
request
.
disable_event_timestamp
:
now
=
datetime
.
now
()
return
datetime
(
1970
,
1
,
1
),
now
if
not
request
.
start_ts
or
not
request
.
end_ts
:
raise
ValueError
(
"start_ts and end_ts are required when disable_event_timestamp is False"
)
try
:
start_date
=
utils
.
make_tzaware
(
parser
.
parse
(
request
.
start_ts
))
end_date
=
utils
.
make_tzaware
(
parser
.
parse
(
request
.
end_ts
))
except
(
ValueError
,
TypeError
)
as
e
:
raise
ValueError
(
f"Invalid timestamp format:
{
e
}
"
)
from
e
if
start_date
>=
end_date
:
raise
ValueError
(
f"start_ts (
{
start_date
}
) must be before end_ts (
{
end_date
}
)"
)
return
start_date
,
end_date
def
get_app
(
store
:
"feast.FeatureStore"
,
registry_ttl_sec
:
int
=
DEFAULT_FEATURE_SERVER_REGISTRY_TTL
,
):
"""
Creates a FastAPI app that can be used to start a feature server.
Args:
store: The FeatureStore to use for serving features
registry_ttl_sec: The TTL in seconds for the registry cache
Returns:
A FastAPI app
Example:
```python
from feast import FeatureStore
store = FeatureStore(repo_path="feature_repo")
app = get_app(store)
```
The app provides the following endpoints:
- `/get-online-features`: Get online features
- `/search`: Vector similarity search (RAG)
- `/retrieve-online-documents`: Deprecated alias for `/search`
- `/v1/vector_stores`: List vector stores (GET)
- `/v1/vector_stores/{vector_store_id}`: Get a vector store (GET)
- `/v1/vector_stores/{vector_store_id}/search`: OpenAI-compatible vector search
- `/push`: Push features to the feature store
- `/write-to-online-store`: Write to the online store
- `/health`: Health check
- `/materialize`: Materialize features
- `/materialize-incremental`: Materialize features incrementally
- `/chat`: Chat UI
- `/ws/chat`: WebSocket endpoint for chat
MCP Support:
- If MCP is enabled in feature server configuration, MCP endpoints will be added automatically
"""
proto_json
.
patch
()
# Asynchronously refresh registry, notifying shutdown and canceling the active timer if the app is shutting down
shutting_down
=
False
active_timer
:
Optional
[
threading
.
Timer
]
=
None
# --- Offline write batching config and batcher ---
fs_cfg
=
getattr
(
store
.
config
,
"feature_server"
,
None
)
batching_cfg
=
None
if
fs_cfg
is
not
None
:
enabled
=
getattr
(
fs_cfg
,
"offline_push_batching_enabled"
,
False
)
batch_size
=
getattr
(
fs_cfg
,
"offline_push_batching_batch_size"
,
None
)
batch_interval_seconds
=
getattr
(
fs_cfg
,
"offline_push_batching_batch_interval_seconds"
,
None
)
if
enabled
is
True
:
size_ok
=
isinstance
(
batch_size
,
int
)
and
not
isinstance
(
batch_size
,
bool
)
interval_ok
=
isinstance
(
batch_interval_seconds
,
int
)
and
not
isinstance
(
batch_interval_seconds
,
bool
)
if
size_ok
and
interval_ok
:
batching_cfg
=
SimpleNamespace
(
enabled
=
True
,
batch_size
=
batch_size
,
batch_interval_seconds
=
batch_interval_seconds
,
)
else
:
logger
.
warning
(
"Offline write batching enabled but missing or invalid numeric values; "
"disabling batching (batch_size=%r, batch_interval_seconds=%r)"
,
batch_size
,
batch_interval_seconds
,
)
offline_batcher
:
Optional
[
OfflineWriteBatcher
]
=
None
if
batching_cfg
is
not
None
and
batching_cfg
.
enabled
is
True
:
offline_batcher
=
OfflineWriteBatcher
(
store
=
store
,
cfg
=
batching_cfg
)
logger
.
debug
(
"Offline write batching is ENABLED"
)
else
:
logger
.
debug
(
"Offline write batching is DISABLED"
)
# Dedicated pool for async materialize so long Spark/offline waits do not
# starve the default executor used by online serving and run_in_threadpool.
_mat_workers_raw
=
os
.
environ
.
get
(
"FEAST_MATERIALIZE_MAX_WORKERS"
,
"2"
)
try
:
materialize_max_workers
=
max
(
1
,
int
(
_mat_workers_raw
))
except
ValueError
:
logger
.
warning
(
"Invalid FEAST_MATERIALIZE_MAX_WORKERS=%r; using default 2"
,
_mat_workers_raw
,
)
materialize_max_workers
=
2
materialize_executor
=
ThreadPoolExecutor
(
max_workers
=
materialize_max_workers
,
thread_name_prefix
=
"feast-materialize"
,
)
def
stop_refresh
():
nonlocal
shutting_down
shutting_down
=
True
if
active_timer
:
active_timer
.
cancel
()
vs_registry
=
VectorStoreRegistry
(
store
)
def
async_refresh
():
if
shutting_down
:
return
store
.
refresh_registry
()
vs_registry
.
refresh
()
if
registry_ttl_sec
:
nonlocal
active_timer
active_timer
=
threading
.
Timer
(
registry_ttl_sec
,
async_refresh
)
active_timer
.
start
()
@
asynccontextmanager
async
def
lifespan
(
app
:
FastAPI
):
# Load static artifacts before initializing store
await
load_static_artifacts
(
app
,
store
)
await
store
.
initialize
()
async_refresh
()
try
:
yield
finally
:
stop_refresh
()
if
offline_batcher
is
not
None
:
offline_batcher
.
shutdown
()
# wait=False: do not block process exit on in-flight materialize
# (same fire-and-forget contract as returning 202 mid-job).
materialize_executor
.
shutdown
(
wait
=
False
)
await
store
.
close
()
app
=
FastAPI
(
lifespan
=
lifespan
)
@
app
.
post
(
"/get-online-features"
,
dependencies
=
[
Depends
(
inject_user_details
)],
response_model
=
OnlineFeaturesResponse
,
)
async
def
get_online_features
(
request
:
GetOnlineFeaturesRequest
)
->
Any
:
with
feast_metrics
.
track_request_latency
(
"/get-online-features"
,
)
as
metrics_ctx
:
features
=
await
_get_features
(
request
,
store
)
feat_count
,
fv_count
=
_resolve_feature_counts
(
features
)
metrics_ctx
.
feature_count
=
feat_count
metrics_ctx
.
feature_view_count
=
fv_count
entity_count
=
len
(
next
(
iter
(
request
.
entities
.
values
()), []))
feast_metrics
.
track_online_features_entities
(
entity_count
)
read_params
=
dict
(
features
=
features
,
entity_rows
=
request
.
entities
,
full_feature_names
=
request
.
full_feature_names
,
include_feature_view_version_metadata
=
request
.
include_feature_view_version_metadata
,
)
audit_start_ms
=
time
.
monotonic
()
*
1000
audit_status
=
"success"
try
:
if
store
.
_get_provider
().
async_supported
.
online
.
read
:
response
=
await
store
.
get_online_features_async
(
**
read_params
)
# type: ignore
else
:
response
=
await
run_in_threadpool
(
lambda
:
store
.
get_online_features
(
**
read_params
)
# type: ignore
)
except
Exception
:
audit_status
=
"error"
raise
finally
:
audit_latency_ms
=
time
.
monotonic
()
*
1000
-
audit_start_ms
_emit_online_audit
(
request
,
features
,
entity_count
,
audit_status
,
audit_latency_ms
)
response_dict
=
await
run_in_threadpool
(
convert_response_to_dict
,
response
.
proto
)
return
JSONResponse
(
content
=
response_dict
)
async
def
_search_online_documents
(
request
:
GetOnlineDocumentsRequest
,
*
,
metrics_path
:
str
,
)
->
JSONResponse
:
with
feast_metrics
.
track_request_latency
(
metrics_path
):
features
=
await
_get_features
(
request
,
store
)
read_params
=
dict
(
features
=
features
,
query
=
request
.
query
,
top_k
=
request
.
top_k
,
)
if
request
.
api_version
==
2
and
request
.
query_string
is
not
None
:
read_params
[
"query_string"
]
=
request
.
query_string
if
request
.
api_version
==
2
and
request
.
distance_metric
is
not
None
:
read_params
[
"distance_metric"
]
=
request
.
distance_metric
if
request
.
api_version
==
2
and
request
.
filters
is
not
None
:
read_params
[
"filters"
]
=
request
.
filters
if
request
.
api_version
==
2
:
read_params
[
"include_feature_view_version_metadata"
]
=
(
request
.
include_feature_view_version_metadata
)
response
=
await
run_in_threadpool
(
lambda
:
store
.
retrieve_online_documents_v2
(
**
read_params
)
# type: ignore
)
else
:
response
=
await
run_in_threadpool
(
lambda
:
store
.
retrieve_online_documents
(
**
read_params
)
# type: ignore
)
response_dict
=
await
run_in_threadpool
(
convert_response_to_dict
,
response
.
proto
)
return
JSONResponse
(
content
=
response_dict
)
@
app
.
post
(
"/search"
,
dependencies
=
[
Depends
(
inject_user_details
)],
response_model
=
OnlineFeaturesResponse
,
)
async
def
search
(
request
:
GetOnlineDocumentsRequest
)
->
JSONResponse
:
"""Vector similarity search against online document embeddings."""
return
await
_search_online_documents
(
request
,
metrics_path
=
"/search"
)
@
app
.
post
(
"/retrieve-online-documents"
,
dependencies
=
[
Depends
(
inject_user_details
)],
response_model
=
OnlineFeaturesResponse
,
include_in_schema
=
False
,
)
async
def
retrieve_online_documents
(
request
:
GetOnlineDocumentsRequest
,
)
->
JSONResponse
:
logger
.
warning
(
"POST /retrieve-online-documents is deprecated; use POST /search instead."
)
return
await
_search_online_documents
(
request
,
metrics_path
=
"/retrieve-online-documents"
)
@
app
.
get
(
"/v1/vector_stores"
,
dependencies
=
[
Depends
(
inject_user_details
)],
)
async
def
list_vector_stores
()
->
JSONResponse
:
permitted
:
list
=
[]
for
obj
in
vs_registry
.
list_vector_stores
():
fv
=
vs_registry
.
resolve
(
obj
[
"id"
])
try
:
assert_permissions
(
resource
=
fv
,
actions
=
[
AuthzedAction
.
DESCRIBE
])
permitted
.
append
(
obj
)
except
Exception
:
pass
return
JSONResponse
(
content
=
{
"object"
:
"list"
,
"data"
:
permitted
})
@
app
.
get
(
"/v1/vector_stores/{vector_store_id}"
,
dependencies
=
[
Depends
(
inject_user_details
)],
)
async
def
get_vector_store
(
vector_store_id
:
str
)
->
JSONResponse
:
try
:
fv
=
vs_registry
.
resolve
(
vector_store_id
)
assert_permissions
(
resource
=
fv
,
actions
=
[
AuthzedAction
.
DESCRIBE
])
except
FeatureViewNotFoundException
:
return
JSONResponse
(
status_code
=
404
,
content
=
{
"error"
: {
"message"
:
f"No vector store found with id '
{
vector_store_id
}
'"
,
"type"
:
"not_found_error"
,
}
},
)
return
JSONResponse
(
content
=
build_vector_store_object
(
store
.
project
,
fv
))
@
app
.
post
(
"/v1/vector_stores/{vector_store_id}/search"
,
dependencies
=
[
Depends
(
inject_user_details
)],
)
async
def
vector_store_search
(
vector_store_id
:
str
,
request
:
OpenAISearchRequest
,
)
->
JSONResponse
:
with
feast_metrics
.
track_request_latency
(
"/v1/vector_stores/{vector_store_id}/search"
):
try
:
feature_view
=
vs_registry
.
resolve
(
vector_store_id
)
assert_permissions
(
resource
=
feature_view
,
actions
=
[
AuthzedAction
.
READ_ONLINE
],
)
result
=
await
store
.
openai_search
(
vector_store_id
=
feature_view
.
name
,
query
=
request
.
query
,
vs_id
=
vector_store_id
,
max_num_results
=
request
.
max_num_results
or
10
,
filters
=
request
.
filters
,
ranking_options
=
(
request
.
ranking_options
.
model_dump
()
if
request
.
ranking_options
else
None
),
rewrite_query
=
request
.
rewrite_query
,
features_to_retrieve
=
(
request
.
metadata
.
features_to_retrieve
if
request
.
metadata
else
None
),
)
except
FeatureViewNotFoundException
:
return
JSONResponse
(
status_code
=
404
,
content
=
{
"error"
: {
"message"
:
f"No vector store found with id '
{
vector_store_id
}
'"
,
"type"
:
"not_found_error"
,
}
},
)
except
ValueError
as
e
:
return
JSONResponse
(
status_code
=
422
,
content
=
{
"error"
: {
"message"
:
str
(
e
),
"type"
:
"invalid_request_error"
,
}
},
)
return
JSONResponse
(
content
=
result
)
@
app
.
post
(
"/push"
,
dependencies
=
[
Depends
(
inject_user_details
)])
async
def
push
(
request
:
PushFeaturesRequest
)
->
Response
:
with
feast_metrics
.
track_request_latency
(
"/push"
):
df
=
pd
.
DataFrame
(
request
.
df
)
actions
=
[]
if
request
.
to
==
"offline"
:
to
=
PushMode
.
OFFLINE
actions
=
[
AuthzedAction
.
WRITE_OFFLINE
]
elif
request
.
to
==
"online"
:
to
=
PushMode
.
ONLINE
actions
=
[
AuthzedAction
.
WRITE_ONLINE
]
elif
request
.
to
==
"online_and_offline"
:
to
=
PushMode
.
ONLINE_AND_OFFLINE
actions
=
WRITE
else
:
raise
ValueError
(
f"
{
request
.
to
}
is not a supported push format. Please specify one of these ['online', 'offline', 'online_and_offline']."
)
from
feast
.
data_source
import
PushSource
all_fvs
=
store
.
list_feature_views
(
allow_cache
=
request
.
allow_registry_cache
)
+
store
.
list_stream_feature_views
(
allow_cache
=
request
.
allow_registry_cache
)
fvs_with_push_sources
=
{
fv
for
fv
in
all_fvs
if
(
fv
.
stream_source
is
not
None
and
isinstance
(
fv
.
stream_source
,
PushSource
)
and
fv
.
stream_source
.
name
==
request
.
push_source_name
)
}
for
feature_view
in
fvs_with_push_sources
:
assert_permissions
(
resource
=
feature_view
,
actions
=
actions
)
async
def
_push_with_to
(
push_to
:
PushMode
)
->
None
:
"""
Helper for performing a single push operation.
NOTE:
- Feast providers **do not currently support async offline writes**.
- Therefore:
* ONLINE and ONLINE_AND_OFFLINE → may be async, depending on provider.async_supported.online.write
* OFFLINE → always synchronous, but executed via run_in_threadpool when called from HTTP handlers.
- The OfflineWriteBatcher handles offline writes directly in its own background thread, but the offline store writes are currently synchronous only.
"""
push_source_name
=
request
.
push_source_name
allow_registry_cache
=
request
.
allow_registry_cache
transform_on_write
=
request
.
transform_on_write
# Async currently only applies to online store writes (ONLINE / ONLINE_AND_OFFLINE paths) as theres no async for offline store
if
push_to
in
(
PushMode
.
ONLINE
,
PushMode
.
ONLINE_AND_OFFLINE
)
and
(
store
.
_get_provider
().
async_supported
.
online
.
write
):
await
store
.
push_async
(
push_source_name
=
push_source_name
,
df
=
df
,
allow_registry_cache
=
allow_registry_cache
,
to
=
push_to
,
transform_on_write
=
transform_on_write
,
)
else
:
await
run_in_threadpool
(
lambda
:
store
.
push
(
push_source_name
=
push_source_name
,
df
=
df
,
allow_registry_cache
=
allow_registry_cache
,
to
=
push_to
,
transform_on_write
=
transform_on_write
,
)
)
needs_online
=
to
in
(
PushMode
.
ONLINE
,
PushMode
.
ONLINE_AND_OFFLINE
)
needs_offline
=
to
in
(
PushMode
.
OFFLINE
,
PushMode
.
ONLINE_AND_OFFLINE
)
status_code
=
status
.
HTTP_200_OK
if
offline_batcher
is
None
or
not
needs_offline
:
await
_push_with_to
(
to
)
else
:
if
needs_online
:
await
_push_with_to
(
PushMode
.
ONLINE
)
offline_batcher
.
enqueue
(
push_source_name
=
request
.
push_source_name
,
df
=
df
,
allow_registry_cache
=
request
.
allow_registry_cache
,
transform_on_write
=
request
.
transform_on_write
,
)
status_code
=
status
.
HTTP_202_ACCEPTED
feast_metrics
.
track_push
(
request
.
push_source_name
,
request
.
to
)
return
Response
(
status_code
=
status_code
)
async
def
_get_feast_object
(
feature_view_name
:
str
,
allow_registry_cache
:
bool
)
->
FeastObject
:
return
await
run_in_threadpool
(
get_feature_view_from_feature_store
,
store
,
feature_view_name
,
allow_registry_cache
,
)
@
app
.
post
(
"/write-to-online-store"
,
dependencies
=
[
Depends
(
inject_user_details
)])
async
def
write_to_online_store
(
request
:
WriteToFeatureStoreRequest
)
->
None
:
df
=
pd
.
DataFrame
(
request
.
df
)
feature_view_name
=
request
.
feature_view_name
allow_registry_cache
=
request
.
allow_registry_cache
resource
=
await
_get_feast_object
(
feature_view_name
,
allow_registry_cache
)
assert_permissions
(
resource
=
resource
,
actions
=
[
AuthzedAction
.
WRITE_ONLINE
])
await
run_in_threadpool
(
store
.
write_to_online_store
,
feature_view_name
=
feature_view_name
,
df
=
df
,
allow_registry_cache
=
allow_registry_cache
,
transform_on_write
=
request
.
transform_on_write
,
)
@
app
.
get
(
"/health"
)
async
def
health
():
try
:
store
.
registry
.
list_projects
(
allow_cache
=
True
)
return
Response
(
status_code
=
status
.
HTTP_200_OK
)
except
Exception
:
return
Response
(
status_code
=
status
.
HTTP_503_SERVICE_UNAVAILABLE
)
@
app
.
post
(
"/chat"
)
async
def
chat
(
request
:
ChatRequest
):
# Process the chat request
# For now, just return dummy text
return
{
"response"
:
"This is a dummy response from the Feast feature server."
}
@
app
.
get
(
"/chat"
)
async
def
chat_ui
():
# Serve the chat UI
static_dir_ref
=
importlib_resources
.
files
(
__spec__
.
parent
)
/
"static/chat"
# type: ignore[name-defined, arg-type]
with
importlib_resources
.
as_file
(
static_dir_ref
)
as
static_dir
:
with
open
(
os
.
path
.
join
(
static_dir
,
"index.html"
))
as
f
:
content
=
f
.
read
()
return
Response
(
content
=
content
,
media_type
=
"text/html"
)
@
app
.
post
(
"/materialize"
,
dependencies
=
[
Depends
(
inject_user_details
)])
async
def
materialize
(
request
:
MaterializeRequest
,
async_mode
:
bool
=
Query
(
False
,
alias
=
"async"
),
force
:
bool
=
Query
(
False
),
):
with
feast_metrics
.
track_request_latency
(
"/materialize"
):
fv_names
=
_authorize_materialize_views
(
store
,
request
.
feature_views
,
version
=
request
.
version
)
start_date
,
end_date
=
_parse_materialize_timestamps
(
request
)
if
async_mode
:
if
force
:
_reset_stuck_materializing_to_generated
(
store
,
fv_names
)
else
:
conflict
=
_check_already_materializing
(
store
,
fv_names
)
if
conflict
:
return
conflict
# Reserve MATERIALIZING before 202 so concurrent requests hit 409.
# store.materialize() treats already-MATERIALIZING as a no-op.
_update_fv_state
(
store
,
fv_names
,
FeatureViewState
.
MATERIALIZING
)
def
_run_materialize
():
try
:
store
.
materialize
(
start_date
,
end_date
,
fv_names
,
disable_event_timestamp
=
request
.
disable_event_timestamp
,
full_feature_names
=
request
.
full_feature_names
,
version
=
request
.
version
,
)
except
Exception
as
e
:
logger
.
error
(
f"Async materialization failed for
{
fv_names
}
:
{
e
}
"
,
exc_info
=
True
,
)
_reset_stuck_materializing_to_generated
(
store
,
fv_names
)
loop
=
asyncio
.
get_running_loop
()
loop
.
run_in_executor
(
materialize_executor
,
_run_materialize
)
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL