Skip to content

Commit 3000b3a

Browse files
committed
fix: Answer online requests that carry zero entity rows
Three empty-input shapes reached internal exceptions, and the feature server turned each into an HTTP 500: entity_rows=[] -> IndexError: list index out of range entities={"driver_id": []} -> KeyError: Missing join key values for keys: [] entities={} -> KeyError: 'pop from an empty set' The middle case is a well-formed request. The join key was supplied, it simply has no values, which is what a caller sends when the upstream query matched nothing that run. get_online_features built its columnar dict from entity_rows[0] on both the sync and async paths, so an empty list raised before anything else ran. _validate_entity_values ended with set_of_row_lengths.pop(); for a mapping with no columns the set is empty and pop() raised. Report zero rows instead. _get_unique_entities treated a join key present with zero values the same as a join key never supplied, even though the row-wise conversion just below it already returns empty results for that case. Raise only when nothing at all was supplied for the view, which leaves the existing behaviour intact: a partially supplied key set still proceeds, and a caller that supplied nothing relevant still errors with the same message listing the expected keys. That error is now MissingJoinKeyValuesException, carrying HTTP 400 so the server reports a client error rather than a 500. It subclasses KeyError as well, since that is what this condition raised before and callers catch it. Signed-off-by: Daksha1611 <mehtadaksha1611@gmail.com>
1 parent 5ad5592 commit 3000b3a

4 files changed

Lines changed: 90 additions & 8 deletions

File tree

‎sdk/python/feast/errors.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,24 @@ def __init__(self):
507507
)
508508

509509

510+
class MissingJoinKeyValuesException(FeastError, KeyError):
511+
"""A required join key was not supplied for the requested feature views.
512+
513+
Subclasses ``KeyError`` as well, because that is what this condition raised
514+
before it carried an HTTP status, and callers catch it.
515+
"""
516+
517+
def __init__(self, missing_keys, empty_keys, provided_keys):
518+
super().__init__(
519+
f"Missing join key values for keys: {sorted(missing_keys)}. "
520+
f"No values provided for keys: {sorted(empty_keys)}. "
521+
f"Provided join_key_values: {list(provided_keys)}"
522+
)
523+
524+
def http_status_code(self) -> int:
525+
return HttpStatusCode.HTTP_400_BAD_REQUEST
526+
527+
510528
class PushSourceNotFoundException(FeastError):
511529
def __init__(self, push_source_name: str):
512530
super().__init__(f"Unable to find push source '{push_source_name}'.")

‎sdk/python/feast/infra/online_stores/online_store.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,10 @@ def get_online_features(
166166
include_feature_view_version_metadata: bool = False,
167167
) -> OnlineResponse:
168168
if isinstance(entity_rows, list):
169-
columnar: Dict[str, List[Any]] = {k: [] for k in entity_rows[0].keys()}
169+
# An empty batch carries no column names; downstream handles zero rows.
170+
columnar: Dict[str, List[Any]] = (
171+
{k: [] for k in entity_rows[0].keys()} if entity_rows else {}
172+
)
170173
for entity_row in entity_rows:
171174
for key, value in entity_row.items():
172175
try:
@@ -450,7 +453,10 @@ async def get_online_features_async(
450453
include_feature_view_version_metadata: bool = False,
451454
) -> OnlineResponse:
452455
if isinstance(entity_rows, list):
453-
columnar: Dict[str, List[Any]] = {k: [] for k in entity_rows[0].keys()}
456+
# An empty batch carries no column names; downstream handles zero rows.
457+
columnar: Dict[str, List[Any]] = (
458+
{k: [] for k in entity_rows[0].keys()} if entity_rows else {}
459+
)
454460
for entity_row in entity_rows:
455461
for key, value in entity_row.items():
456462
try:

‎sdk/python/feast/utils.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from feast.errors import (
3434
FeatureNameCollisionError,
3535
FeatureViewNotFoundException,
36+
MissingJoinKeyValuesException,
3637
RequestDataNotFoundInEntityRowsException,
3738
)
3839
from feast.field import Field
@@ -556,7 +557,8 @@ def _validate_entity_values(join_key_values: Dict[str, List[ValueProto]]):
556557
set_of_row_lengths = {len(v) for v in join_key_values.values()}
557558
if len(set_of_row_lengths) > 1:
558559
raise ValueError("All entity rows must have the same columns.")
559-
return set_of_row_lengths.pop()
560+
# No columns at all means no rows; popping an empty set would raise here.
561+
return set_of_row_lengths.pop() if set_of_row_lengths else 0
560562

561563

562564
def _validate_feature_refs(feature_refs: List[str], full_feature_names: bool = False):
@@ -1025,11 +1027,13 @@ def _get_unique_entities(
10251027
)
10261028

10271029
if missing_keys or empty_keys:
1028-
if not any(table_entity_values.values()):
1029-
raise KeyError(
1030-
f"Missing join key values for keys: {missing_keys}. "
1031-
f"No values provided for keys: {empty_keys}. "
1032-
f"Provided join_key_values: {list(join_key_values.keys())}"
1030+
# Columns present but all empty is a well-formed request that simply has
1031+
# no rows this run; the row-wise conversion below already returns empty
1032+
# results for it. Only a caller that supplied nothing at all for this
1033+
# view is reporting an error.
1034+
if not table_entity_values:
1035+
raise MissingJoinKeyValuesException(
1036+
missing_keys, empty_keys, join_key_values.keys()
10331037
)
10341038

10351039
# Convert the column-oriented table_entity_values into row-wise data.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""An empty batch of entities must not surface internal errors.
2+
3+
A caller whose upstream query matched nothing sends zero rows. That used to hit
4+
``IndexError: list index out of range`` or ``KeyError: 'pop from an empty set'``,
5+
which the feature server turned into a 500.
6+
"""
7+
8+
import pytest
9+
from fastapi import status as HttpStatusCode
10+
11+
from feast.errors import MissingJoinKeyValuesException
12+
from feast.utils import _validate_entity_values
13+
from tests.utils.cli_repo_creator import CliRunner, get_example_repo
14+
15+
FEATURES = ["driver_locations:lat", "driver_locations:lon"]
16+
17+
18+
def test_validate_entity_values_treats_no_columns_as_zero_rows():
19+
"""Popping the empty set raised instead of reporting zero rows."""
20+
assert _validate_entity_values({}) == 0
21+
22+
23+
def test_missing_join_key_values_is_a_client_error():
24+
exc = MissingJoinKeyValuesException(["driver_id"], [], [])
25+
# Callers caught KeyError before this carried a status; keep that working.
26+
assert isinstance(exc, KeyError)
27+
assert exc.http_status_code() == HttpStatusCode.HTTP_400_BAD_REQUEST
28+
29+
30+
def test_join_key_present_with_zero_values_returns_an_empty_response():
31+
"""A well-formed request that simply has no rows this run."""
32+
runner = CliRunner()
33+
with runner.local_repo(
34+
get_example_repo("example_feature_repo_1.py"), "file"
35+
) as store:
36+
response = store.get_online_features(
37+
features=FEATURES, entity_rows={"driver_id": []}
38+
).to_dict()
39+
40+
assert set(response.keys()) == {"driver_id", "lat", "lon"}
41+
assert all(values == [] for values in response.values())
42+
43+
44+
@pytest.mark.parametrize("entity_rows", [[], {}], ids=["empty_list", "no_columns"])
45+
def test_request_without_join_keys_raises_a_client_error(entity_rows):
46+
"""No column names at all: report the missing join key, not an internal error."""
47+
runner = CliRunner()
48+
with runner.local_repo(
49+
get_example_repo("example_feature_repo_1.py"), "file"
50+
) as store:
51+
with pytest.raises(MissingJoinKeyValuesException) as excinfo:
52+
store.get_online_features(features=FEATURES, entity_rows=entity_rows)
53+
54+
assert "driver_id" in str(excinfo.value)

0 commit comments

Comments
 (0)