ankitdhandharia commented on code in PR #41427:
URL: https://github.com/apache/beam/pull/41427#discussion_r4672836159
##########
sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store.py:
##########
@@ -157,6 +159,7 @@ def __enter__(self):
self.features = self.store.get_feature_service(
self.feature_service_name)
except Exception:
+ self._remove_local_repo_path()
Review Comment:
Done in cd11a08da2a: `__enter__` now sets `self.store = None` before
cleaning up and raising, and the feature-service test checks that `store` is
`None` afterwards.
##########
sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store.py:
##########
@@ -183,18 +186,50 @@ def __call__(self, request: beam.Row, *args, **kwargs):
# Since we do this per entity, the list of feature values only contain
# a single element at position 0.
response_dict = {k: v[0] for k, v in feature_values.items()}
+ # The entity key columns are echoed back by Feast and are not features;
+ # a feature that is absent from the online store comes back as `None`.
+ missing_features = [
+ name for name, value in response_dict.items()
+ if name not in entity_dict and value is None
+ ]
+ if missing_features:
+ if self._exception_level == ExceptionLevel.RAISE:
+ raise ValueError(
+ 'No feature values found for features %s for the entity: %s.' %
+ (missing_features, entity_dict))
+ if self._exception_level == ExceptionLevel.WARN:
+ _LOGGER.warning(
+ 'No feature values found for features %s for the entity: %s.',
+ missing_features,
+ entity_dict)
return request, beam.Row(**response_dict)
+ def _remove_local_repo_path(self):
+ """Delete the temp feature-store YAML downloaded in `__enter__`."""
+ local_repo_path = getattr(self, '_local_repo_path', None)
+ if local_repo_path:
+ try:
+ os.remove(local_repo_path)
+ except OSError:
+ pass
+ self._local_repo_path = None
+
def __exit__(self, exc_type, exc_val, exc_tb):
"""Clean the instantiated Feast feature store client."""
self.store = None
+ self._remove_local_repo_path()
def get_cache_key(self, request: beam.Row) -> str:
"""Returns a string formatted with unique entity-id for the feature values.
"""
if self.entity_row_fn:
entity_dict = self.entity_row_fn(request)
- entity_id = list(entity_dict.keys())[0]
- else:
- entity_id = self.entity_id
- return 'entity_id: %s' % request._asdict()[entity_id]
+ # Build the cache key from the entity key/value pairs returned by
+ # `entity_row_fn`. The returned mapping may use entity names that are not
+ # columns on the input row, so we must not index back into the request.
+ # Sorting keeps the key stable and collision-free for compound
+ # (multi-entity) mappings.
+ key = ', '.join(
+ '%s: %s' % (name, entity_dict[name]) for name in sorted(entity_dict))
Review Comment:
Good catch, thanks. In cd11a08da2a the key is now `'entity_id: %r' %
(sorted(entity_dict.items()), )`. I used `repr` over `json.dumps` so entity
values that are not JSON-serializable still work. I also added
`test_get_cache_key_with_entity_row_fn_is_unambiguous`, which covers `{'a': 1}`
vs `{'a': '1'}` and `{'a': '1, b: 2'}` vs `{'a': '1', 'b': '2'}`.
##########
sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_test.py:
##########
@@ -61,5 +67,119 @@ def test_feast_enrichment_invalid_args(self, entity_id,
entity_row_fn):
)
+class TestFeastFeatureStoreHandlerUnit(unittest.TestCase):
+ """CPU-only unit tests that mock out GCS and the Feast feature store."""
+ _MODULE = 'apache_beam.transforms.enrichment_handlers.feast_feature_store'
+ _YAML_PATH = 'gs://dummy-bucket/feature_store.yaml'
+
+ def _build_handler(self, **kwargs):
+ # Skip the gs:// existence check so the handler can be built without GCS.
+ with mock.patch(self._MODULE +
'._validate_feature_store_yaml_path_exists'):
+ return FeastFeatureStoreEnrichmentHandler(
+ feature_store_yaml_path=self._YAML_PATH, **kwargs)
+
+ def test_get_cache_key_with_mapped_entity_row_fn(self):
+ # `entity_row_fn` maps the input column `id` to a differently-named entity
+ # key `user_id`. The cache key must be derived from the value the function
+ # returns, not by re-indexing the input row (which has no `user_id`).
+ handler = self._build_handler(
+ feature_names=['x'], entity_row_fn=lambda row: {'user_id': row.id})
+ self.assertEqual(
+ handler.get_cache_key(beam.Row(id=5)), 'entity_id: user_id: 5')
+
+ def test_get_cache_key_with_compound_entity_row_fn(self):
+ # Compound (multi-entity) mappings must produce a stable, order-independent
+ # key.
+ handler = self._build_handler(
+ feature_names=['x'],
+ entity_row_fn=lambda row: {
+ 'user_id': row.id, 'country': row.country
+ })
+ self.assertEqual(
+ handler.get_cache_key(beam.Row(id=5, country='US')),
+ 'entity_id: country: US, user_id: 5')
+
+ def test_call_raises_when_features_missing_and_level_raise(self):
+ handler = self._build_handler(
+ entity_id='user_id',
+ feature_names=['state'],
+ exception_level=ExceptionLevel.RAISE)
+ handler.features = ['state']
+ handler.store = mock.MagicMock()
+ handler.store.get_online_features.return_value.to_dict.return_value = {
+ 'user_id': [1], 'state': [None]
+ }
+ with self.assertRaises(ValueError):
+ handler(beam.Row(user_id=1))
+
+ def test_call_warns_when_features_missing_and_level_warn(self):
+ handler = self._build_handler(
+ entity_id='user_id',
+ feature_names=['state'],
+ exception_level=ExceptionLevel.WARN)
+ handler.features = ['state']
+ handler.store = mock.MagicMock()
+ handler.store.get_online_features.return_value.to_dict.return_value = {
+ 'user_id': [1], 'state': [None]
+ }
+ with self.assertLogs(feast_feature_store._LOGGER, level='WARNING') as logs:
+ _, response = handler(beam.Row(user_id=1))
+ self.assertTrue(any('state' in message for message in logs.output))
+ self.assertIsNone(response.state)
+
+ def test_call_does_not_warn_when_features_present(self):
Review Comment:
Added `test_call_is_silent_when_features_missing_and_level_quiet` in
cd11a08da2a. It checks that nothing is logged at WARNING, that no exception is
raised, and that the missing feature comes back as `None`.
##########
sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_test.py:
##########
@@ -61,5 +67,119 @@ def test_feast_enrichment_invalid_args(self, entity_id,
entity_row_fn):
)
+class TestFeastFeatureStoreHandlerUnit(unittest.TestCase):
Review Comment:
Done: `TestFeastFeatureStoreHandlerUnit` now has `@pytest.mark.uses_feast`
(cd11a08da2a), and `-m uses_feast` picks up all 9 of its tests locally. Once
#41595 is merged I'll touch `.github/trigger_files/beam_PostCommit_Python.json`
here to kick off the PostCommit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]