diff --git a/docs/how-to-guides/online-server-performance-tuning.md b/docs/how-to-guides/online-server-performance-tuning.md index fc0c0f56528..33887a76770 100644 --- a/docs/how-to-guides/online-server-performance-tuning.md +++ b/docs/how-to-guides/online-server-performance-tuning.md @@ -37,6 +37,8 @@ When the server processes a `get_online_features()` call, it groups the requeste **PostgreSQL exception:** PostgreSQL stores each feature view in its own table and overrides `_read_features_per_fv()` to combine the per-view reads into a **single `UNION ALL` statement**, so a request touching any number of feature views costs **1** query on both the sync and async paths. This helps most where round trips dominate — a handful of entities against a remote database. Requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) fall back to one query per view, because at that size the saved round trips no longer offset holding every view's rows at once. A single-view request is never batched, since there is nothing to combine. Set `max_batched_result_rows: 0` in the online store config to turn batching off. As with Redis, consolidating feature views still reduces application-layer overhead. **DynamoDB exception:** DynamoDB stores each feature view in its own table and overrides `_read_features_per_fv()` to pack the keys of every feature view into **shared `BatchGetItem` requests**, since one request can read from several tables. A request touching any number of feature views costs as few as **1** request (up to `batch_size` keys per request, sent in parallel) on both the sync and async paths. As with PostgreSQL, requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one view at a time, single-view requests are never batched, and `max_batched_result_rows: 0` turns batching off. + +**Bigtable exception:** Bigtable keeps every feature view keyed on the same entities in one shared table, with rows keyed `{entity_id}#{feature_view_name}`, and overrides `_read_features_per_fv()` to fetch the rows of all those views with **one `ReadRows` call per table**. A request touching any number of feature views on the same entities costs **1** call; views on different entity sets cost one call per entity set. This applies to the sync path, which is the only read path Bigtable has. As with PostgreSQL and DynamoDB, requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one view at a time, single-view requests are never batched, and `max_batched_result_rows: 0` turns batching off. The call's row filter selects, for the rows of each view, only the features requested from that view. A request whose filter would come close to Bigtable's 20 KB row filter limit also reads one view at a time. {% endhint %} ### Feature services are free (and can be faster) @@ -289,7 +291,7 @@ The online store is the single largest factor in `get_online_features()` latency | **PostgreSQL** | 3–10 ms | No (threadpool) | Teams with existing Postgres infra; all FV reads batched into 1 query | Connection pooling needed at scale | | **MongoDB** | 2–5 ms | Yes | Flexible schema, async-native | Requires index tuning for large datasets | | **Aerospike** | < 1 ms | No (threadpool) | Ultra-low latency, hybrid memory (RAM + SSD), large datasets | Namespace must be pre-configured on the cluster | -| **Bigtable** | 3–8 ms | No (threadpool) | Large-scale GCP workloads | Row-key design affects read performance | +| **Bigtable** | 3–8 ms | No (threadpool) | Large-scale GCP workloads; FV reads on the same entities batched into 1 `ReadRows` call | Row-key design affects read performance | | **Cassandra / ScyllaDB** | 2–5 ms | No (threadpool) | Multi-region, write-heavy | Tunable consistency; requires DC-aware routing | | **Remote** | Varies | No (threadpool) | Centralized feature server architecture | Adds an HTTP hop; tune connection pool | | **SQLite** | N/A | No | Local development only | No concurrent access; not suitable for production | diff --git a/docs/reference/online-stores/bigtable.md b/docs/reference/online-stores/bigtable.md index 0d6e7cfb13b..b81e7d41f56 100644 --- a/docs/reference/online-stores/bigtable.md +++ b/docs/reference/online-stores/bigtable.md @@ -29,6 +29,10 @@ online_store: The full set of configuration options is available in [BigtableOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.bigtable.BigtableOnlineStoreConfig). +## Batched Multi-Feature-View Reads + +Feature views keyed on the same entities share one Bigtable table. When a request spans several feature views, the rows of all the views in a table are fetched with a single `ReadRows` call, so a request for 10 feature views on the same entities costs **1** call instead of 10. Requests larger than `max_batched_result_rows` (entity rows × feature views, default 2048) read one feature view at a time instead. The row filter of that call matches each view's rows by row key and selects only the features requested from that view, so a batched read returns the same cells as the per-view reads. Requests whose filter would come close to Bigtable's 20 KB row filter limit, which takes several hundred requested features in one table, read one feature view at a time, and so do requests naming a feature view whose name is not plain ASCII. A single-view request is never batched. Set `max_batched_result_rows: 0` to turn batching off. + ## Functionality Matrix The set of functionality supported by online stores is described in detail [here](overview.md#functionality). diff --git a/sdk/python/feast/infra/online_stores/bigtable.py b/sdk/python/feast/infra/online_stores/bigtable.py index c4f84e1ef56..ccc4af5e2e5 100644 --- a/sdk/python/feast/infra/online_stores/bigtable.py +++ b/sdk/python/feast/infra/online_stores/bigtable.py @@ -1,5 +1,6 @@ import hashlib import logging +import re from concurrent import futures from datetime import datetime from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple @@ -7,7 +8,7 @@ import google from google.cloud import bigtable from google.cloud.bigtable import row_filters -from pydantic import PositiveInt, StrictStr +from pydantic import NonNegativeInt, PositiveInt, StrictStr from feast import Entity, FeatureView, utils from feast.feature_view import DUMMY_ENTITY_NAME @@ -27,6 +28,20 @@ # library limits the connection pool size to 10, which bounds the useful concurrency. # Overridable via ``BigtableOnlineStoreConfig.write_concurrency``. BIGTABLE_CLIENT_CONNECTION_POOL_SIZE = 10 +# Default for ``BigtableOnlineStoreConfig.max_batched_result_rows``: the largest +# request, measured as entity rows x feature views, whose feature views are read with +# one ReadRows call per Bigtable table. Past it each view is read on its own, so that +# the rows of every view are not held at once. +MAX_BATCHED_RESULT_ROWS = 2048 +# Bigtable rejects a row filter larger than 20 KB +# (https://cloud.google.com/bigtable/quotas#limits-filters). One batched read carries +# the row key pattern and the requested features of every view of a table in a single +# filter, so a request whose filter would pass this size reads one feature view at a +# time instead. +MAX_BATCHED_FILTER_BYTES = 16_000 +# Upper bound on what one feature view adds to the serialized filter of a batched read +# on top of its two regexes: the tags and lengths of its chain and of both conditions. +BATCHED_FILTER_VIEW_OVERHEAD_BYTES = 32 class BigtableOnlineStoreConfig(FeastConfigBaseModel): @@ -54,6 +69,11 @@ class BigtableOnlineStoreConfig(FeastConfigBaseModel): per worker during ``online_write_batch``. Lower values reduce the write load placed on the Bigtable instance at the cost of longer materialization. Defaults to 10.""" + max_batched_result_rows: NonNegativeInt = MAX_BATCHED_RESULT_ROWS + """(optional) Largest request, as entity rows x feature views, whose feature views + are read with one ReadRows call per Bigtable table. Set to 0 to always read one + feature view at a time. Defaults to 2048.""" + class BigtableOnlineStore(OnlineStore): _client: Optional[bigtable.Client] = None @@ -67,14 +87,10 @@ def online_read( entity_keys: List[EntityKeyProto], requested_features: Optional[List[str]] = None, ) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]: - # Potential performance improvement opportunity described in - # https://github.com/feast-dev/feast/issues/3259 + # Requests spanning several feature views are batched per Bigtable table by + # `_read_features_per_fv`; see https://github.com/feast-dev/feast/issues/3259 feature_view = table bt_table_name = self._get_table_name(config=config, feature_view=feature_view) - - client = self._get_client(online_config=config.online_store) - bt_instance = client.instance(instance_id=config.online_store.instance) - bt_table = bt_instance.table(bt_table_name) row_keys = [ self._compute_row_key( entity_key=entity_key, @@ -83,29 +99,214 @@ def online_read( ) for entity_key in entity_keys ] + bt_rows_dict = self._read_rows( + config, bt_table_name, row_keys, self._column_filter(requested_features) + ) + return [self._process_bt_row(bt_rows_dict.get(row_key)) for row_key in row_keys] - row_set = bigtable.row_set.RowSet() - for row_key in row_keys: - row_set.add_row_key(row_key) - rows = bt_table.read_rows( - row_set=row_set, - filter_=( - row_filters.ColumnQualifierRegexFilter( - f"^({'|'.join(requested_features)}|event_ts)$".encode() + def _read_features_per_fv( + self, + config: RepoConfig, + grouped_refs: List, + join_key_values: Dict, + entity_name_to_join_key_map: Dict, + online_features_response, + full_feature_names: bool, + include_feature_view_version_metadata: bool, + ) -> None: + """Read every requested feature view with one ReadRows call per Bigtable table. + + Feature views keyed on the same entities share a Bigtable table, and each + view's rows are keyed ``{entity_id}#{feature_view_name}``, so the rows of all + those views are fetched together instead of one ReadRows call per view. The + filter of that call selects, for the rows of each view, the columns requested + from that view, so it returns the same cells as the per-view reads. + """ + + def read_one_view_at_a_time() -> None: + super(BigtableOnlineStore, self)._read_features_per_fv( + config, + grouped_refs, + join_key_values, + entity_name_to_join_key_map, + online_features_response, + full_feature_names, + include_feature_view_version_metadata, + ) + + if not self._should_batch(config, grouped_refs, join_key_values): + return read_one_view_at_a_time() + + reads = [] + keys_by_table: Dict[str, Dict[bytes, None]] = {} + # Per Bigtable table and feature view: the features requested from the view, + # where None stands for every column. One feature view requested under two + # aliases reads the same rows, so its row keys are deduplicated and its + # requested features merged. + views_by_table: Dict[str, Dict[str, Optional[Set[str]]]] = {} + for table, requested_features in grouped_refs: + table_entity_values, idxs, output_len = utils._get_unique_entities( + table, join_key_values, entity_name_to_join_key_map + ) + row_keys = [ + self._compute_row_key( + entity_key=entity_key, feature_view_name=table.name, config=config ) - if requested_features + for entity_key in utils._get_entity_key_protos(table_entity_values) + ] + reads.append((table, requested_features, row_keys, idxs, output_len)) + + bt_table_name = self._get_table_name(config=config, feature_view=table) + keys_by_table.setdefault(bt_table_name, {}).update(dict.fromkeys(row_keys)) + views = views_by_table.setdefault(bt_table_name, {}) + requested = views.get(table.name, set()) + views[table.name] = ( + requested | set(requested_features) + if requested is not None and requested_features else None - ), + ) + + filters_by_table: Dict[str, Optional[row_filters.RowFilter]] = {} + for bt_table_name, views in views_by_table.items(): + if not all(name.isascii() and name.isprintable() for name in views): + # The row key patterns of the filter are only built for names that + # are plain ASCII. + return read_one_view_at_a_time() + if self._batched_filter_size(views) > MAX_BATCHED_FILTER_BYTES: + return read_one_view_at_a_time() + filters_by_table[bt_table_name] = self._batched_filter(views) + + # A row key names its feature view, and a feature view lives in one table, so + # the rows of every table can be indexed by row key alone. Each row is decoded + # once, however many aliases of its view were requested. + rows: Dict[ + bytes, Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]] + ] = {} + for bt_table_name, table_row_keys in keys_by_table.items(): + bt_rows = self._read_rows( + config, + bt_table_name, + list(table_row_keys), + filters_by_table[bt_table_name], + ) + for row_key, row in bt_rows.items(): + rows[row_key] = self._process_bt_row(row) + + for table, requested_features, row_keys, idxs, output_len in reads: + utils._populate_response_from_feature_data( + requested_features, + [rows.get(row_key, (None, None)) for row_key in row_keys], + idxs, + online_features_response, + full_feature_names, + table, + output_len, + include_feature_view_version_metadata, + ) + + @staticmethod + def _should_batch( + config: RepoConfig, grouped_refs: List, join_key_values: Dict + ) -> bool: + """Whether to read this request's feature views together. + + A single view has nothing to share a ReadRows call with. The number of entity + rows in the request bounds the unique keys any one view reads, so the size is + estimated from the request shape. See :data:`MAX_BATCHED_RESULT_ROWS`. + """ + if len(grouped_refs) < 2: + return False + entity_rows = max( + (len(values) for values in join_key_values.values()), default=0 + ) + return ( + entity_rows * len(grouped_refs) + <= config.online_store.max_batched_result_rows + ) + + @classmethod + def _batched_filter( + cls, views: Dict[str, Optional[Set[str]]] + ) -> Optional[row_filters.RowFilter]: + """The filter of one read of a table's feature views. + + ``views`` maps each feature view to the features requested from it, or to None + when it is read without a feature list. A view's rows only pass the columns + requested from that view: its condition is tied to its row keys, which end in + the view's name. So a column stored under a feature name that was only + requested from another view is not read, whether or not the view's current + schema still lists it. + """ + if len(views) == 1: + return cls._column_filter(cls._sorted(next(iter(views.values())))) + per_view: List[row_filters.RowFilter] = [] + for name, requested in views.items(): + row_key_filter = row_filters.RowKeyRegexFilter(cls._row_key_regex(name)) + column_filter = cls._column_filter(cls._sorted(requested)) + per_view.append( + row_filters.RowFilterChain(filters=[row_key_filter, column_filter]) + if column_filter is not None + else row_key_filter + ) + return row_filters.RowFilterUnion(filters=per_view) + + @classmethod + def _batched_filter_size(cls, views: Dict[str, Optional[Set[str]]]) -> int: + """An upper bound on the serialized size of :meth:`_batched_filter`.""" + return sum( + len(cls._row_key_regex(name)) + + (len(cls._column_filter_regex(sorted(requested))) if requested else 0) + + BATCHED_FILTER_VIEW_OVERHEAD_BYTES + for name, requested in views.items() + ) + + @staticmethod + def _row_key_regex(feature_view_name: str) -> bytes: + """Matches the row keys of one feature view; see :meth:`_compute_row_key`. + + The entity id is a hex digest, so the first ``#`` of a row key ends it and a + row key matches the pattern of exactly one feature view. + """ + return f"^[0-9a-f]+#{re.escape(feature_view_name)}$".encode() + + @staticmethod + def _sorted(requested: Optional[Set[str]]) -> Optional[List[str]]: + return sorted(requested) if requested is not None else None + + @classmethod + def _column_filter( + cls, requested_features: Optional[List[str]] + ) -> Optional[row_filters.RowFilter]: + if not requested_features: + return None + return row_filters.ColumnQualifierRegexFilter( + cls._column_filter_regex(requested_features) ) + @staticmethod + def _column_filter_regex(requested_features: List[str]) -> bytes: + return f"^({'|'.join(requested_features)}|event_ts)$".encode() + + def _read_rows( + self, + config: RepoConfig, + bt_table_name: str, + row_keys: List[bytes], + filter_: Optional[row_filters.RowFilter], + ) -> Dict[bytes, bigtable.row.PartialRowData]: + client = self._get_client(online_config=config.online_store) + bt_instance = client.instance(instance_id=config.online_store.instance) + bt_table = bt_instance.table(bt_table_name) + + row_set = bigtable.row_set.RowSet() + for row_key in row_keys: + row_set.add_row_key(row_key) + rows = bt_table.read_rows(row_set=row_set, filter_=filter_) + # The BigTable client library only returns rows for keys that are found. This # means that it's our responsibility to match the returned rows to the original - # `row_keys` and make sure that we're returning a list of the same length as - # `entity_keys`. - bt_rows_dict: Dict[bytes, bigtable.row.PartialRowData] = { - row.row_key: row for row in rows - } - return [self._process_bt_row(bt_rows_dict.get(row_key)) for row_key in row_keys] + # `row_keys`, so the rows are returned by key. + return {row.row_key: row for row in rows} def _process_bt_row( self, row: Optional[bigtable.row.PartialRowData] diff --git a/sdk/python/tests/unit/infra/online_store/test_bigtable_batched_read.py b/sdk/python/tests/unit/infra/online_store/test_bigtable_batched_read.py new file mode 100644 index 00000000000..acf19095d04 --- /dev/null +++ b/sdk/python/tests/unit/infra/online_store/test_bigtable_batched_read.py @@ -0,0 +1,467 @@ +"""Unit tests for batching Bigtable online reads across feature views.""" + +import re +from datetime import timedelta +from typing import Dict, List, Tuple +from unittest.mock import patch + +import pytest + +pytest.importorskip("google.cloud.bigtable") + +from google.cloud.bigtable import row_filters # noqa: E402 +from pydantic import ValidationError # noqa: E402 + +from feast import Entity, FeatureView # noqa: E402 +from feast.field import Field # noqa: E402 +from feast.infra.offline_stores.dask import DaskOfflineStoreConfig # noqa: E402 +from feast.infra.online_stores.bigtable import ( # noqa: E402 + MAX_BATCHED_FILTER_BYTES, + MAX_BATCHED_RESULT_ROWS, + BigtableOnlineStore, + BigtableOnlineStoreConfig, +) +from feast.infra.online_stores.online_store import OnlineStore # noqa: E402 +from feast.protos.feast.serving.ServingService_pb2 import ( # noqa: E402 + FieldStatus, + GetOnlineFeaturesResponse, +) +from feast.protos.feast.types.EntityKey_pb2 import ( # noqa: E402 + EntityKey as EntityKeyProto, +) +from feast.protos.feast.types.Value_pb2 import Value as ValueProto # noqa: E402 +from feast.repo_config import RepoConfig # noqa: E402 +from feast.types import Int64 # noqa: E402 +from feast.utils import _utc_now # noqa: E402 +from feast.value_type import ValueType # noqa: E402 + +DRIVER = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64) +CUSTOMER = Entity( + name="customer", join_keys=["customer_id"], value_type=ValueType.INT64 +) +JOIN_KEY_MAP = {"driver": "driver_id", "customer": "customer_id"} + + +def _feature_view( + name: str, features: List[str], entity: Entity = DRIVER +) -> FeatureView: + return FeatureView( + name=name, + entities=[entity], + ttl=timedelta(days=1), + schema=[Field(name=feature, dtype=Int64) for feature in features], + ) + + +def _config(**online_store) -> RepoConfig: + return RepoConfig( + registry="s3://test_registry/registry.db", + project="test_bigtable", + provider="gcp", + online_store=BigtableOnlineStoreConfig( + instance="test-instance", **online_store + ), + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + + +class _Cell: + def __init__(self, value: bytes): + self.value = value + + +class _Row: + def __init__(self, row_key: bytes, columns: Dict[bytes, bytes]): + self.row_key = row_key + # A fresh dict per read, as the client builds one per response. + self.cells = { + "features": {name: [_Cell(value)] for name, value in columns.items()} + } + + +def _passes(filter_, row_key: bytes, column: bytes) -> bool: + """Whether a cell passes ``filter_``, for the filter types the store builds.""" + if filter_ is None: + return True + if isinstance(filter_, row_filters.RowFilterUnion): + return any(_passes(f, row_key, column) for f in filter_.filters) + if isinstance(filter_, row_filters.RowFilterChain): + return all(_passes(f, row_key, column) for f in filter_.filters) + if isinstance(filter_, row_filters.RowKeyRegexFilter): + return re.fullmatch(filter_.regex, row_key) is not None + assert isinstance(filter_, row_filters.ColumnQualifierRegexFilter) + return re.fullmatch(filter_.regex, column) is not None + + +class _FakeBigtable: + """Serves read_rows from in-memory tables and records every call.""" + + def __init__(self): + self.tables: Dict[str, Dict[bytes, Dict[bytes, bytes]]] = {} + self.calls: List[Tuple[str, List[bytes]]] = [] + # (row key, column) of every feature cell returned, event_ts aside. + self.cells: List[Tuple[bytes, bytes]] = [] + + def instance(self, instance_id): + return self + + def table(self, table_name): + fake = self + + class _Table: + def read_rows(self, row_set, filter_=None): + fake.calls.append((table_name, list(row_set.row_keys))) + stored = fake.tables.get(table_name, {}) + for row_key in row_set.row_keys: + if row_key in stored: + columns = { + name: value + for name, value in stored[row_key].items() + if _passes(filter_, row_key, name) + } + if not columns: + continue + fake.cells.extend( + (row_key, name) for name in columns if name != b"event_ts" + ) + yield _Row(row_key, columns) + + return _Table() + + +def _write(store, config, fake, fv: FeatureView, join_key: str, rows: dict) -> None: + """Store ``{entity value: {feature: value}}`` the way online_write_batch does.""" + table = fake.tables.setdefault( + store._get_table_name(config=config, feature_view=fv), {} + ) + event_ts = _utc_now().isoformat().encode() + for entity_value, values in rows.items(): + entity_key = EntityKeyProto( + join_keys=[join_key], entity_values=[ValueProto(int64_val=entity_value)] + ) + row_key = store._compute_row_key( + entity_key=entity_key, feature_view_name=fv.name, config=config + ) + table[row_key] = { + **{ + name.encode(): ValueProto(int64_val=value).SerializeToString() + for name, value in values.items() + }, + b"event_ts": event_ts, + } + + +def _drivers(*ids) -> dict: + return {"driver_id": [ValueProto(int64_val=i) for i in ids]} + + +def _read(store, config, fake, grouped_refs, join_key_values, generic=False): + """Run one read and return the response and the read_rows calls it made.""" + fake.calls.clear() + fake.cells.clear() + response = GetOnlineFeaturesResponse() + read = OnlineStore._read_features_per_fv if generic else store._read_features_per_fv + with patch.object(BigtableOnlineStore, "_get_client", return_value=fake): + if generic: + read( + store, + config, + grouped_refs, + join_key_values, + JOIN_KEY_MAP, + response, + True, + False, + ) + else: + read( + config, + grouped_refs, + join_key_values, + JOIN_KEY_MAP, + response, + True, + False, + ) + return response, list(fake.calls) + + +def _values(response) -> Dict[str, list]: + names = response.metadata.feature_names.val + return { + name: [ + (value.int64_val if status == FieldStatus.PRESENT else None) + for value, status in zip(vector.values, vector.statuses) + ] + for name, vector in zip(names, response.results) + } + + +@pytest.fixture +def setup(): + store, config, fake = BigtableOnlineStore(), _config(), _FakeBigtable() + return store, config, fake + + +def test_views_on_same_entities_share_one_read_rows_call(setup): + store, config, fake = setup + views = [_feature_view(f"fv{i}", [f"f{i}"]) for i in range(3)] + for i, fv in enumerate(views): + _write(store, config, fake, fv, "driver_id", {1: {f"f{i}": 10 + i}}) + grouped_refs = [(fv, [f"f{i}"]) for i, fv in enumerate(views)] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + generic, generic_calls = _read( + store, config, fake, grouped_refs, _drivers(1, 2), generic=True + ) + + assert len(calls) == 1 and len(calls[0][1]) == 6 + assert len(generic_calls) == 3 + assert response == generic + assert _values(response) == { + "fv0__f0": [10, None], + "fv1__f1": [11, None], + "fv2__f2": [12, None], + } + + +def test_views_on_different_entities_read_once_per_table(setup): + store, config, fake = setup + by_driver = _feature_view("by_driver", ["trips"]) + also_by_driver = _feature_view("also_by_driver", ["rating"]) + by_customer = _feature_view("by_customer", ["orders"], entity=CUSTOMER) + _write(store, config, fake, by_driver, "driver_id", {1: {"trips": 5}}) + _write(store, config, fake, also_by_driver, "driver_id", {1: {"rating": 4}}) + _write(store, config, fake, by_customer, "customer_id", {7: {"orders": 3}}) + grouped_refs = [ + (by_driver, ["trips"]), + (by_customer, ["orders"]), + (also_by_driver, ["rating"]), + ] + join_key_values = { + **_drivers(1, 1), + "customer_id": [ValueProto(int64_val=7), ValueProto(int64_val=8)], + } + + response, calls = _read(store, config, fake, grouped_refs, join_key_values) + generic, _ = _read(store, config, fake, grouped_refs, join_key_values, generic=True) + + assert len(calls) == 2 + assert response == generic + assert _values(response) == { + "by_driver__trips": [5, 5], + "by_customer__orders": [3, None], + "also_by_driver__rating": [4, 4], + } + + +def test_same_feature_name_does_not_leak_across_views(setup): + store, config, fake = setup + fv_a = _feature_view("fv_a", ["score", "extra"]) + fv_b = _feature_view("fv_b", ["score"]) + _write(store, config, fake, fv_a, "driver_id", {1: {"score": 1, "extra": 9}}) + _write(store, config, fake, fv_b, "driver_id", {2: {"score": 2}}) + grouped_refs = [(fv_a, ["score"]), (fv_b, ["score"])] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + + assert len(calls) == 1 + assert _values(response) == {"fv_a__score": [1, None], "fv_b__score": [None, 2]} + assert ( + response + == _read(store, config, fake, grouped_refs, _drivers(1, 2), generic=True)[0] + ) + + +def test_one_view_under_two_aliases_reads_its_rows_once(setup): + store, config, fake = setup + fv = _feature_view("fv", ["a", "b"]) + _write(store, config, fake, fv, "driver_id", {1: {"a": 1, "b": 2}}) + grouped_refs = [(fv.with_name("first"), ["a"]), (fv.with_name("second"), ["b"])] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 3)) + + assert len(calls) == 1 and len(calls[0][1]) == 2 + assert _values(response) == {"first__a": [1, None], "second__b": [2, None]} + assert ( + response + == _read(store, config, fake, grouped_refs, _drivers(1, 3), generic=True)[0] + ) + + +def test_single_view_keeps_the_generic_path(setup): + store, config, fake = setup + fv = _feature_view("fv", ["a"]) + _write(store, config, fake, fv, "driver_id", {1: {"a": 1}}) + + with patch.object( + OnlineStore, "_read_features_per_fv", autospec=True + ) as generic_read: + _read(store, config, fake, [(fv, ["a"])], _drivers(1)) + + generic_read.assert_called_once() + + +@pytest.mark.parametrize("limit, expected_calls", [(0, 2), (3, 2), (4, 1)]) +def test_max_batched_result_rows_limits_batching(setup, limit, expected_calls): + store, _, fake = setup + config = _config(max_batched_result_rows=limit) + views = [_feature_view("fv_x", ["x"]), _feature_view("fv_y", ["y"])] + grouped_refs = [(views[0], ["x"]), (views[1], ["y"])] + + # 2 entity rows x 2 feature views = 4 result rows. + _, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + + assert len(calls) == expected_calls + + +@pytest.mark.parametrize("extra_bytes, expected_calls", [(0, 1), (1, 2)]) +def test_filter_over_the_size_limit_reads_one_view_at_a_time( + setup, extra_bytes, expected_calls +): + store, config, fake = setup + # The filter of the batched read carries the features of both views. The last + # name is padded so that the filter is exactly at the limit, or one byte over. + names = [f"{i:02d}".ljust(560, "x") for i in range(28)] + requested = {"fv_a": set(names[:14]), "fv_b": set(names[14:])} + padding = MAX_BATCHED_FILTER_BYTES - store._batched_filter_size(requested) + assert padding > 0 + names[-1] += "x" * (padding + extra_bytes) + requested["fv_b"] = set(names[14:]) + assert ( + store._batched_filter_size(requested) == MAX_BATCHED_FILTER_BYTES + extra_bytes + ) + views = [_feature_view("fv_a", names[:14]), _feature_view("fv_b", names[14:])] + grouped_refs = [(views[0], names[:14]), (views[1], names[14:])] + for fv, features in grouped_refs: + _write( + store, + config, + fake, + fv, + "driver_id", + {1: {name: n for n, name in enumerate(features)}}, + ) + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + generic, _ = _read(store, config, fake, grouped_refs, _drivers(1, 2), generic=True) + + assert len(calls) == expected_calls + assert response == generic + assert _values(response)[f"fv_b__{names[14]}"] == [0, None] + + +def test_filter_size_bounds_the_serialized_filter(setup): + store, _, _ = setup + requested = { + "fv_a": {"score", "extra"}, + "fv_b": None, + "fv_c": {f"feature_{i}" for i in range(300)}, + } + + filter_ = store._batched_filter(requested) + # to_pb was renamed _to_pb in newer releases of the client. + filter_pb = getattr(filter_, "_to_pb", None) or filter_.to_pb + serialized = type(filter_pb()).serialize(filter_pb()) + + assert len(serialized) <= store._batched_filter_size(requested) + + +@pytest.mark.parametrize( + "requested_a, requested_b", + [ + # Both views store "score" and "extra", and each is asked for one of them. + (["score"], ["extra"]), + # fv_b is read without a feature list, fv_a is not. + (["score"], []), + (["score"], ["score"]), + (["score", "extra"], ["extra", "score"]), + ], +) +def test_unrequested_columns_are_not_read(setup, requested_a, requested_b): + store, config, fake = setup + fv_a = _feature_view("fv_a", ["score", "extra"]) + fv_b = _feature_view("fv_b", ["score", "extra"]) + _write(store, config, fake, fv_a, "driver_id", {1: {"score": 1, "extra": 9}}) + _write(store, config, fake, fv_b, "driver_id", {1: {"score": 2, "extra": 8}}) + grouped_refs = [(fv_a, requested_a), (fv_b, requested_b)] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + cells = sorted(fake.cells) + generic, _ = _read(store, config, fake, grouped_refs, _drivers(1, 2), generic=True) + + assert len(calls) == 1 + assert cells == sorted(fake.cells) + assert response == generic + + +def test_column_removed_from_the_schema_is_not_read(setup): + store, config, fake = setup + # fv_a used to have a "payload" feature. Removing a feature from a view leaves + # its cells in Bigtable, so the rows of fv_a still hold a "payload" column that + # the view's schema no longer lists. + fv_a = _feature_view("fv_a", ["score"]) + fv_b = _feature_view("fv_b", ["payload"]) + _write(store, config, fake, fv_a, "driver_id", {1: {"score": 1, "payload": 9}}) + _write(store, config, fake, fv_b, "driver_id", {1: {"payload": 2}}) + grouped_refs = [(fv_a, ["score"]), (fv_b, ["payload"])] + fv_a_row_key = store._compute_row_key( + entity_key=EntityKeyProto( + join_keys=["driver_id"], entity_values=[ValueProto(int64_val=1)] + ), + feature_view_name="fv_a", + config=config, + ) + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + cells = sorted(fake.cells) + generic, _ = _read(store, config, fake, grouped_refs, _drivers(1, 2), generic=True) + + assert len(calls) == 1 + assert (fv_a_row_key, b"payload") not in cells + assert cells == sorted(fake.cells) + assert response == generic + assert _values(response) == {"fv_a__score": [1, None], "fv_b__payload": [2, None]} + + +def test_filter_tells_apart_views_with_similar_names(setup): + store, config, fake = setup + # One name ends with another, and "." in a name is not a regex wildcard. + names = ["fv", "x#fv", "a.b", "aXb"] + views = [_feature_view(name, ["score", "extra"]) for name in names] + for i, fv in enumerate(views): + _write(store, config, fake, fv, "driver_id", {1: {"score": i, "extra": 9}}) + grouped_refs = [ + (fv, [feature]) for fv, feature in zip(views, ["score", "extra"] * 2) + ] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1, 2)) + cells = sorted(fake.cells) + generic, _ = _read(store, config, fake, grouped_refs, _drivers(1, 2), generic=True) + + assert len(calls) == 1 + assert len(cells) == 4 + assert cells == sorted(fake.cells) + assert response == generic + + +def test_non_ascii_view_name_reads_one_view_at_a_time(setup): + store, config, fake = setup + views = [_feature_view("fv_a", ["a"]), _feature_view("fv_\u00e9", ["b"])] + _write(store, config, fake, views[0], "driver_id", {1: {"a": 1}}) + _write(store, config, fake, views[1], "driver_id", {1: {"b": 2}}) + grouped_refs = [(views[0], ["a"]), (views[1], ["b"])] + + response, calls = _read(store, config, fake, grouped_refs, _drivers(1)) + generic, _ = _read(store, config, fake, grouped_refs, _drivers(1), generic=True) + + assert len(calls) == 2 + assert response == generic + + +def test_max_batched_result_rows_default_and_validation(): + config = BigtableOnlineStoreConfig(instance="test-instance") + assert config.max_batched_result_rows == MAX_BATCHED_RESULT_ROWS == 2048 + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig(instance="test-instance", max_batched_result_rows=-1)