From 57db91265b3568187a657be607ea3fa08cd9d2b5 Mon Sep 17 00:00:00 2001 From: Timothy Smallwood Date: Fri, 20 Nov 2026 13:22:33 -0600 Subject: [PATCH] feat: Add Bigtable online store support for the Go feature server Add a read-only Bigtable online store to the Go feature server. It reads the tables Python's `feast materialize` writes, with no data migration, and takes the same `online_store` section of feature_store.yaml. - Table `.` with Python's md5 shortening, row key hex(murmur3_x64_128(entity key v3)) + "#" + feature view, family `features`, one qualifier per feature plus `event_ts`. - Reads are split into chunks of `keys_per_request` row keys (default 5), up to `max_concurrent_chunks` per read (default 50), each a ReadRows filtered to the requested qualifiers and LatestNFilter(1). `read_timeout_ms` (default 60 s) bounds each read, including retries. - Optional `max_inflight_reads` caps ReadRows calls across the server. A read reserves all the slots it needs before it sends anything, and is rejected (RESOURCE_EXHAUSTED over gRPC, 500 over HTTP) when they are not free within `max_inflight_wait_ms` (default 0, reject at once), so an overloaded server sheds whole reads instead of queueing them until they time out. - Optional `adaptive_chunking` keeps `keys_per_request` as the smallest chunk and grows chunks, up to 100 keys, so a large read goes out in one round. - Optional `disable_metrics` turns off the client's Cloud Monitoring export. A `bigtable.OnlineRead` span and Prometheus series for read duration, chunks sent and rows found. - Add the optional EntityAwareOnlineStore interface: readFromOnlineStore passes each view's entity names from the request's own view snapshot, so stream views keep precedence. OnlineRead returns an error wrapping errors.ErrUnsupported. The OnlineStore interface and the other stores are unchanged. - After the client primes its connections, startup pings the instance once more, so the emulator gets the same check and NotFound (no tables yet, or a mistyped instance) logs a warning; on an emulator, Unimplemented also only warns. An unset project_id falls back to GOOGLE_CLOUD_PROJECT, GCLOUD_PROJECT, then the default credentials' project. - Python: accept the Go settings in BigtableOnlineStoreConfig so one feature_store.yaml serves both; Python online reads use `app_profile`; add `write_app_profile` (keeps writes off the serving profile) and `initial_tablets` (pre-split new tables so a small table is not served by one node), each off unless set. The numeric Go settings are strict ints up to MaxInt32, as the Go server parses them, so `feast apply` rejects what the Go server would. - Parity fixtures are generated from the in-tree Python store, and a Python unit test fails when they drift, with or without Feast's proto_json patch applied. An end-to-end Go test has the Python SDK apply and materialize into the Bigtable emulator, then reads it back through GetOnlineFeatures; CI's Go job installs the gcp extra for it. - Docs for the Go reader and the new Python settings, linked from the feature_store.yaml reference. Signed-off-by: Timothy Smallwood --- .github/workflows/unit_tests.yml | 2 + .pre-commit-config.yaml | 3 +- docs/reference/feature-store-yaml.md | 2 +- docs/reference/online-stores/bigtable.md | 184 +- go.mod | 11 +- go.sum | 6 + go/README.md | 12 +- go/internal/feast/featurestore.go | 24 +- .../feast/featurestore_bigtable_test.go | 133 ++ go/internal/feast/featurestore_test.go | 138 ++ .../feast/onlinestore/bigtableconfig.go | 181 ++ .../feast/onlinestore/bigtableonlinestore.go | 936 +++++++++++ .../bigtableonlinestore_helpers_test.go | 80 + .../bigtableonlinestore_read_test.go | 1484 +++++++++++++++++ .../onlinestore/bigtableonlinestore_test.go | 556 ++++++ go/internal/feast/onlinestore/onlinestore.go | 25 +- .../feast/onlinestore/redisonlinestore.go | 3 - .../testdata/bigtable_fixtures.json | 661 ++++++++ .../testdata/gen_bigtable_fixtures.py | 362 ++++ .../feast/infra/online_stores/bigtable.py | 123 +- .../test_bigtable_batched_read.py | 19 +- .../online_store/test_bigtable_go_fixtures.py | 190 +++ .../test_bigtable_online_store.py | 418 ++++- skills/feast-architecture/SKILL.md | 8 + 24 files changed, 5536 insertions(+), 25 deletions(-) create mode 100644 go/internal/feast/featurestore_bigtable_test.go create mode 100644 go/internal/feast/onlinestore/bigtableconfig.go create mode 100644 go/internal/feast/onlinestore/bigtableonlinestore.go create mode 100644 go/internal/feast/onlinestore/bigtableonlinestore_helpers_test.go create mode 100644 go/internal/feast/onlinestore/bigtableonlinestore_read_test.go create mode 100644 go/internal/feast/onlinestore/bigtableonlinestore_test.go create mode 100644 go/internal/feast/onlinestore/testdata/bigtable_fixtures.json create mode 100644 go/internal/feast/onlinestore/testdata/gen_bigtable_fixtures.py create mode 100644 sdk/python/tests/unit/infra/online_store/test_bigtable_go_fixtures.py diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 2d8b1c044be..9e4a2b5f362 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -133,6 +133,8 @@ jobs: echo "${{ github.workspace }}/.venv/bin" >> $GITHUB_PATH - name: Install feast locally run: make install-feast-locally + - name: Install the gcp extra for the Bigtable end-to-end test + run: uv pip install -e ".[gcp]" - name: Run Go tests with coverage run: | # The Go packages share a registry fixture and must run sequentially. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fcfce78288e..cbf6a048854 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -59,7 +59,8 @@ repos: .*\.lock| .*requirements.*\.txt| .*\.svg| - .*\.html + .*\.html| + go/internal/feast/onlinestore/testdata/bigtable_fixtures\.json )$ - repo: https://github.com/alessandrojcm/commitlint-pre-commit-hook diff --git a/docs/reference/feature-store-yaml.md b/docs/reference/feature-store-yaml.md index f5cc1cecb0a..100f79a0cad 100644 --- a/docs/reference/feature-store-yaml.md +++ b/docs/reference/feature-store-yaml.md @@ -19,7 +19,7 @@ online_store: * **provider** \("local" or "gcp"\) — Defines the environment in which Feast will execute data flows. * **registry** \(a local or GCS filepath\) — Defines the location of the feature registry. -* **online\_store** — Configures the online store. This field will have various subfields depending on the type of online store: +* **online\_store** — Configures the online store. This field will have various subfields depending on the type of online store. Each store's page under [Online stores](online-stores/README.md) lists its options, for example the Bigtable read settings that only the Go feature server uses ([Bigtable](online-stores/bigtable.md#go-feature-server)). The sqlite and datastore options are: * **type** \("sqlite" or "datastore"\) — Defines the type of online store. * **path** \(a local filepath\) — Parameter for the sqlite online store. Defines the path to the SQLite database file. * **project\_id** — Optional parameter for the datastore online store. Sets the GCP project id used by Feast, if not set Feast will use the default GCP project id in the local environment. diff --git a/docs/reference/online-stores/bigtable.md b/docs/reference/online-stores/bigtable.md index b81e7d41f56..e3d2c7b6a82 100644 --- a/docs/reference/online-stores/bigtable.md +++ b/docs/reference/online-stores/bigtable.md @@ -33,6 +33,188 @@ The full set of configuration options is available in 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. +## Table creation and writes + +These settings change how the Python SDK creates tables and writes to them. Each is off unless set, so a +`feature_store.yaml` without them behaves as before. The Go feature server ignores all of them except +`app_profile`, which it uses for its reads too. + +{% code title="feature_store.yaml" %} +```yaml +online_store: + type: bigtable + project_id: my_gcp_project + instance: my_bigtable_instance + app_profile: serving + write_app_profile: materialization + initial_tablets: 128 +``` +{% endcode %} + +| Option | Default | Description | +| ------ | ------- | ----------- | +| `app_profile` | the instance's default app profile | App profile for online reads, by the Python SDK and the Go feature server. | +| `write_app_profile` | the instance's default app profile | App profile for the Python SDK's writes (`feast materialize` and push). It does not fall back to `app_profile`, so setting `app_profile` alone never moves writes onto the serving profile. Point it at an app profile with low request priority so that materialization does not compete with serving reads. | +| `initial_tablets` | unset, no split | When set, `feast apply` creates each new table pre-split into this many tablets, from 2 to 256, at evenly spaced row key prefixes. Existing tables are not changed. | + +Pre-splitting matters for small tables. A new table starts as a single tablet, and Bigtable may keep a +small table on one tablet, served by one node, so every read of a small table, such as one keyed by +`driver`, can land on that node however many nodes the cluster has. Row keys start with a uniform hex +hash, so split points at even hex prefixes give tablets of about the same size. `initial_tablets: 16` +splits at `10`, `20`, ... `f0`. As a rule of thumb, use a few tablets per node at the node count you +expect to run. The maximum is 256. +To pre-split a table without this setting, for example with an older SDK, create it with +[`cbt`](https://cloud.google.com/bigtable/docs/cbt-overview) before `feast apply`, which then leaves the +table as it is and only adds the `features` column family: + +```bash +cbt -project my_gcp_project -instance my_bigtable_instance createtable my_feature_repo.driver "splits=10,20,30,40,50,60,70,80,90,a0,b0,c0,d0,e0,f0" +``` + +The table name is `.`, or `.__dummy` for a +feature view with no entities, and is at most 50 characters. An entity part longer than 24 characters is +replaced by the first 24 hex characters of its md5 hash. A project too long for the rest is replaced by +its first 10 characters, `_`, and as much of its md5 hash in hex as fits. + +## Go feature server + +The Go feature server reads the tables that the Python SDK materializes into Bigtable. It reads the +same `online_store` section of `feature_store.yaml`, plus a few read settings that only it uses. The +Python SDK accepts these settings so that one `feature_store.yaml` works for both, but ignores them. +Python SDK releases from before these options were added reject them (`Extra inputs are not permitted`), +so with an older SDK keep these keys out of the `feature_store.yaml` that `feast apply` and +`feast materialize` read. + +{% code title="feature_store.yaml" %} +```yaml +project: my_feature_repo +registry: data/registry.db +provider: gcp +entity_key_serialization_version: 3 +online_store: + type: bigtable + project_id: my_gcp_project + instance: my_bigtable_instance + max_versions: 1 + app_profile: serving + keys_per_request: 5 + max_concurrent_chunks: 50 + read_timeout_ms: 250 + max_inflight_reads: 300 + max_inflight_wait_ms: 10 + adaptive_chunking: false + disable_metrics: false +``` +{% endcode %} + +| Option | Default | Description | +| ------ | ------- | ----------- | +| `project_id` | `GOOGLE_CLOUD_PROJECT`, then `GCLOUD_PROJECT`, then the project of the default credentials | GCP project of the instance. When unset, the Go feature server takes the first of these that is set, the same order as the Python client, and fails at startup if none is. User credentials from `gcloud auth application-default login` carry no project, so set `project_id` or `GOOGLE_CLOUD_PROJECT` with them and with the emulator. | +| `instance` | required | The Bigtable instance's ID. | +| `max_versions` | `2` | Ignored by the Go feature server, which accepts any value and always reads the latest cell version. The Python SDK uses it as the column family's garbage collection rule. For online serving, `1` is enough. `feast apply` sets the rule when it creates the column family; to change an existing table's rule, use `cbt setgcpolicy`. | +| `app_profile` | the instance's default app profile | Bigtable app profile used for reads, for example one with high request priority, apart from `write_app_profile`. The Python SDK's online reads use it too. The profile must already exist on the instance. | +| `keys_per_request` | `5` | Number of row keys in one `ReadRows` request, from 1 to 100. Each read is split into chunks of this size. Higher values make fewer calls and use less CPU, at the cost of latency. See below. | +| `max_concurrent_chunks` | `50` | Maximum number of chunks that one online read sends to Bigtable at the same time. It limits each read call, not the whole server; `max_inflight_reads` limits the server. Lower values reduce the load on a small instance at the cost of latency for large reads. | +| `read_timeout_ms` | `60000` | Time budget in milliseconds for one online read, including the client's retries and any wait for `max_inflight_reads` slots. The caller's deadline still applies, and the shorter of the two wins. The 60 s default is a ceiling that stops the client retrying without end, not a latency target. Set it near your serving target, for example 250 ms, so that an overloaded server fails reads quickly instead of holding them in memory. | +| `max_inflight_reads` | unset, no limit | Maximum number of `ReadRows` calls in flight across all online reads of the server. A read reserves all the slots it needs, the smallest of its chunk count, `max_concurrent_chunks` and `max_inflight_reads`, before it sends anything, and holds them until it ends. When they are not free within `max_inflight_wait_ms`, the read is rejected with `RESOURCE_EXHAUSTED` and sends nothing to Bigtable. Rejecting early keeps the admitted reads well inside their deadline, so that under overload the server keeps serving what the instance can handle instead of every read slowing down until `read_timeout_ms` fails it. `RESOURCE_EXHAUSTED` is the gRPC code; the HTTP endpoint returns 500 with the same message. Like any failed read, each rejection is logged at error level. Size it to the concurrent calls your instance serves within your latency target, divided by the number of servers, and keep it several times `max_concurrent_chunks`: a read reserves up to `max_concurrent_chunks` slots at once, so a cap near that value rejects large reads whenever anything else is in flight. | +| `max_inflight_wait_ms` | `0` | How long, in milliseconds, a read waits for free `max_inflight_reads` slots before it is rejected. `0` rejects it at once when the cap is full. A short wait, such as 10 to 20, absorbs bursts at the cost of that much latency for the reads that wait. Keep it well below `read_timeout_ms`, which stays the last bound on a read. Applies only when `max_inflight_reads` is set. | +| `adaptive_chunking` | `false` | When `true`, `keys_per_request` is the smallest chunk size, and a read that would need more than `max_concurrent_chunks` chunks gets larger chunks, up to 100 keys, so it fits in that many calls where it can. With the defaults, that is a read of more than 250 row keys. Large reads make fewer calls, but each larger chunk is slower. See below. | +| `disable_metrics` | `false` | When `true`, the Bigtable client exports no client-side metrics to Cloud Monitoring, so the serving identity needs no `monitoring.timeSeries.create` permission, and the server spends less CPU. The startup log's `metrics` field shows which applies. | + +`keys_per_request`, `max_concurrent_chunks`, `read_timeout_ms` and `max_inflight_reads` must be positive +whole numbers and `max_inflight_wait_ms` a whole number from 0, at most 2147483647 and written unquoted: +a quoted value such as `"25"` or a boolean is rejected by `feast apply` and by the Go feature server. +`adaptive_chunking` and `disable_metrics` must be unquoted `true` or `false`. An invalid value fails the +Go feature server at startup rather than at the first request. + +### Startup and permissions + +At startup the Bigtable client primes its connections with `PingAndWarm`, so bad credentials or an +unreachable instance fail startup. The Go feature server then pings the instance once more, within 10 +seconds, which gives the emulator the same check. Two answers only log a warning. One is `NotFound`, +which Bigtable returns for an instance with no tables yet; a mistyped instance, and possibly a mistyped +app profile, also returns it, and reads then fail, so check for this warning. The other is +`Unimplemented` from an emulator too old to support the ping. + +The serving identity needs `bigtable.tables.readRows` and `bigtable.instances.ping`, both in +`roles/bigtable.reader`. The client library also exports client-side metrics to Cloud Monitoring, which +needs `monitoring.timeSeries.create`; without it the client logs one permission error and keeps serving. +Set `disable_metrics: true` to turn the export off. + +### How the Go feature server reads + +* Each online read builds one row key per entity and feature view, splits the row keys into chunks of + `keys_per_request`, and reads up to `max_concurrent_chunks` chunks in parallel. With + `max_inflight_reads` set, the read is first admitted or rejected as a whole (see the table above). The + first chunk that fails cancels the others and fails the read. +* A `ReadRows` request with many row keys can take longer than the same keys sent as several smaller + requests in parallel, so splitting a read into small chunks can cut its latency. The defaults, chunks + of 5 keys with 50 in flight, favor latency on an instance with many nodes. Each chunk is a separate + call, so small chunks cost more CPU in the Go feature server and more requests on Bigtable per read. + On a small instance or at high request rates, raise `keys_per_request`, lower `max_concurrent_chunks` + and set `max_inflight_reads`. +* With `adaptive_chunking: true`, a large read goes out in one round of larger chunks instead of + several rounds of `keys_per_request`. With the defaults, 500 row keys go out as 50 calls of 10 keys + rather than 100 calls of 5 in two rounds, and 1,500 row keys as 50 calls of 30. Chunks never shrink + below `keys_per_request`. The size comes from the read's total row keys and each table is cut + separately, so a read over several tables can plan a few more chunks than `max_concurrent_chunks`; + the extra ones wait for a free slot. A very large read is still slower than one round of small + chunks, because each larger call takes longer; raising `max_concurrent_chunks` + is the other route, at a CPU cost in the Go feature server. The gain also depends on the floor: with + a small `keys_per_request`, such as 2, the extra rounds are short, and a large read can come out + slightly slower with `adaptive_chunking` on, so measure it at your own settings. +* Bigtable's [in-memory tier](https://cloud.google.com/bigtable/docs/in-memory-overview) (Enterprise + Plus edition, in Preview) serves only single-row point reads, so a `ReadRows` request with two or more + row keys is always read from storage. To let the Go feature server use it, set `keys_per_request: 1`, + leave `adaptive_chunking` off so that large reads do not grow back into multi-key requests, and set + `app_profile` to an app profile configured for the in-memory tier. Each row key is then its own request, + which costs more CPU in the Go feature server, so check `max_concurrent_chunks` and + `max_inflight_reads` against the larger request count. The store reads only the newest cell of each + column, so its reads are not the historical-cell reads that the tier never serves. +* Only the latest version of each cell is read, so the Go feature server returns the same values as the + Python SDK whatever `max_versions` is set to. +* Entity join keys must be of type `STRING`, `BYTES`, `INT32` or `INT64`. Other types, such as + `UNIX_TIMESTAMP` or `UUID`, return an error. +* The HTTP endpoint types entity values by their JSON form, not by the entity's declared type: strings + arrive as `STRING` and whole numbers as `INT64`. So `BYTES` and `INT32` join keys are found only through + the gRPC endpoint, with the value sent as `bytes_val` or `int32_val`; over HTTP they return `NOT_FOUND`. + This applies to every Go online store. +* `entity_key_serialization_version` must be `3`, the Python SDK's default. When it is omitted, the Go + feature server uses `3`. Any other value fails at startup. + +### Monitoring and operation + +* The server exports `feast_bigtable_online_read_duration_seconds` by `status` (`ok`, `error`, or + `rejected` for reads that `max_inflight_reads` turned away), and + `feast_bigtable_online_read_chunks_total` (`ReadRows` calls sent) and + `feast_bigtable_online_read_rows_found_total` by `table`, on its metrics port. +* Errors from Bigtable keep their gRPC code, so a gRPC client can also get `RESOURCE_EXHAUSTED` from + Bigtable itself, for example from a quota. Those count under `status="error"`, not `rejected`, and their + message names the table read rather than `max_inflight_reads`. +* With tracing on, each read's `bigtable.OnlineRead` span records its row keys, chunk size, chunks, the + planned rounds of chunks, rows found, and the time it waited for its own `max_concurrent_chunks` slots + (`bigtable.call_slot_wait_ms`) and for admission to `max_inflight_reads` (`bigtable.inflight_wait_ms`), + which separates queueing from time in Bigtable. +* Consider pre-splitting small tables, or every read of one may land on a single node. Set + `initial_tablets` before the first `feast apply`; see + [Table creation and writes](#table-creation-and-writes). + +### Data written by older Feast releases + +The Go feature server reads the row keys that current Python +writes, so rows written with a different entity key encoding are not found (each entity returns +`NOT_FOUND`, with no error). Re-materialize such tables with a current release: + +* Before 0.50, `entity_key_serialization_version` defaulted to `1`. Tables written by those releases with + the setting omitted use version 1 keys. +* Before 0.44, version `3` keys had no entity count prefix (and before 0.40 an explicit `3` wrote + version 2 keys), so tables written with an explicit `3` by any release before 0.44 differ too. +* Before 0.61, the length prefix of each join key name counted characters, not bytes, so tables with + non-ASCII join key names written by 0.44 to 0.60 differ. + +Table names, the column family, the `event_ts` qualifier and its format are unchanged since the Bigtable +online store was added. + ## Functionality Matrix The set of functionality supported by online stores is described in detail [here](overview.md#functionality). @@ -48,7 +230,7 @@ Below is a matrix indicating which functionality is supported by the Bigtable on | support for on-demand transforms | yes | | readable by Python SDK | yes | | readable by Java | no | -| readable by Go | no | +| readable by Go | yes | | support for entityless feature views | yes | | support for concurrent writing to the same key | yes | | support for ttl (time to live) at retrieval | no | diff --git a/go.mod b/go.mod index 8ea7446e613..14ceff5a589 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/feast-dev/feast go 1.26.10 require ( + cloud.google.com/go/bigtable v1.58.0 cloud.google.com/go/storage v1.71.0 github.com/apache/arrow/go/v17 v17.0.0 github.com/aws/aws-sdk-go-v2 v1.48.0 @@ -19,6 +20,7 @@ require ( github.com/mattn/go-sqlite3 v1.14.53 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.25.0 + github.com/prometheus/client_model v0.6.3 github.com/redis/go-redis/v9 v9.23.0 github.com/roberson-io/mmh3 v0.0.0-20190729202758-fdfce3ba6225 github.com/rs/zerolog v1.35.1 @@ -29,7 +31,9 @@ require ( go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 go.opentelemetry.io/otel/sdk v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/oauth2 v0.38.0 golang.org/x/sync v0.25.0 + google.golang.org/api v0.316.0 google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f google.golang.org/grpc v1.85.0 google.golang.org/protobuf v1.36.12 @@ -42,6 +46,7 @@ require ( cloud.google.com/go/auth/oauth2adapt v0.3.1 // indirect cloud.google.com/go/compute/metadata v0.10.0 // indirect cloud.google.com/go/iam v1.15.1 // indirect + cloud.google.com/go/longrunning v1.5.0 // indirect cloud.google.com/go/monitoring v1.32.1 // indirect filippo.io/edwards25519 v1.2.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.63.0 // indirect @@ -77,6 +82,7 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/goccy/go-json v0.12.0 // indirect github.com/golang/snappy v1.0.0 // indirect + github.com/google/btree v1.1.3 // indirect github.com/google/flatbuffers v25.12.19+incompatible // indirect github.com/google/s2a-go v0.1.11 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.25 // indirect @@ -89,6 +95,7 @@ require ( github.com/klauspost/asmfmt v1.3.2 // indirect github.com/klauspost/compress v1.20.5 // indirect github.com/klauspost/cpuid/v2 v2.4.2 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 // indirect @@ -97,7 +104,6 @@ require ( github.com/pandatix/go-abnf v0.5.5 // indirect github.com/pierrec/lz4/v4 v4.1.33 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.74.0 // indirect github.com/prometheus/procfs v0.23.0 // indirect github.com/spiffe/go-spiffe/v2 v2.9.0 // indirect @@ -117,15 +123,14 @@ require ( golang.org/x/exp v0.0.0-20261120182113-8801fbdfac81 // indirect golang.org/x/mod v0.43.0 // indirect golang.org/x/net v0.63.0 // indirect - golang.org/x/oauth2 v0.38.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/telemetry v0.0.0-20261119160235-508b12de1089 // indirect golang.org/x/text v0.44.0 // indirect golang.org/x/time v0.16.0 // indirect golang.org/x/tools v0.53.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect - google.golang.org/api v0.316.0 // indirect google.golang.org/genproto v0.0.0-20261118221215-c8830f628b3f // indirect google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + rsc.io/binaryregexp v0.2.0 // indirect ) diff --git a/go.sum b/go.sum index 11761073ad9..0442c72eaaa 100644 --- a/go.sum +++ b/go.sum @@ -6,6 +6,8 @@ cloud.google.com/go/auth v0.24.4 h1:m49juFKXOaeRwmLgcrd3e4hrwqLDe1+4g8fH0EoznUU= cloud.google.com/go/auth v0.24.4/go.mod h1:p4UXqfSXnMVUDutk9xePzI8lj8yyoJ3BLsKWv0NSvQk= cloud.google.com/go/auth/oauth2adapt v0.3.1 h1:BKLDdbWS7pafd820dsyFDF6fPEzIGqr7ny6hbTzCCgE= cloud.google.com/go/auth/oauth2adapt v0.3.1/go.mod h1:B1nM4FJDxoDqAt3PXFG4IflUoQ5kvWAOOM3R+5wAszg= +cloud.google.com/go/bigtable v1.58.0 h1:fkf7bI0DBkKN85uRrfEEpkbufSc48b4PVIZCRud3xRk= +cloud.google.com/go/bigtable v1.58.0/go.mod h1:fZ/QM3mBog9JYJ5KV1z2xqv2+vfHGvoazGJllGQClds= cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY= cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk= cloud.google.com/go/iam v1.15.1 h1:i6EXLKyIi0Sh72p+5+Fz0PfnzB63bkneVpaBCGrjlWs= @@ -129,6 +131,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/flatbuffers v25.12.19+incompatible h1:haMV2JRRJCe1998HeW/p0X9UaMTK6SDo0ffLn2+DbLs= github.com/google/flatbuffers v25.12.19+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -333,3 +337,5 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/binaryregexp v0.2.0 h1:HfqmD5MEmC0zvwBuF187nq9mdnXjXsSivRiXN7SmRkE= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/go/README.md b/go/README.md index 308787cac9f..be7420e2bbc 100644 --- a/go/README.md +++ b/go/README.md @@ -19,6 +19,9 @@ The server exposes Prometheus metrics at the `/metrics` endpoint on a dedicated Key metrics include: - `http_request_duration_seconds`: Histogram of response latency. - `http_requests_total`: Counter of HTTP requests by status, method, and path. +- `feast_bigtable_online_read_duration_seconds`, `feast_bigtable_online_read_chunks_total` and + `feast_bigtable_online_read_rows_found_total`: Bigtable online store reads, when that store is used + (see `docs/reference/online-stores/bigtable.md`). - Standard Go and Process metrics. A `/health` endpoint is available on the main application port (default `:8080`) for readiness probes. @@ -35,10 +38,11 @@ The default exporter URL is "http://localhost:4318". The default schema of sendi ## List of files have OTEL observability code 1. internal/feast/transformation/transformation.go 2. internal/feast/onlinestore/redisonlinestore.go -3. internal/feast/server/grpc_server.go -4. internal/feast/server/http_server.go -5. internal/feast/server/server_commons.go -6. internal/feast/featurestore.go +3. internal/feast/onlinestore/bigtableonlinestore.go +4. internal/feast/server/grpc_server.go +5. internal/feast/server/http_server.go +6. internal/feast/server/server_commons.go +7. internal/feast/featurestore.go ## Example monitoring infra setup 1. docker compose file to setup Prometheus, Jaeger, and OTEL-collector. diff --git a/go/internal/feast/featurestore.go b/go/internal/feast/featurestore.go index f6abd50e3d1..3466149b24e 100644 --- a/go/internal/feast/featurestore.go +++ b/go/internal/feast/featurestore.go @@ -81,6 +81,10 @@ func NewFeatureStore(config *registry.RepoConfig, callback transformation.Transf }, nil } +// GetOnlineFeatures returns the requested features, named by featureRefs or by featureService, for the +// entity rows in joinKeyToEntityValues. It reads each group of feature views from the online store, then +// applies on-demand feature views using requestData. +// // TODO: Review all functions that use ODFV and Request FV since these have not been tested // ToDo: Split GetOnlineFeatures interface into two: GetOnlinFeaturesByFeatureService and GetOnlineFeaturesByFeatureRefs func (fs *FeatureStore) GetOnlineFeatures( @@ -168,7 +172,7 @@ func (fs *FeatureStore) GetOnlineFeatures( } for _, groupRef := range groupedRefs { - featureData, err := fs.readFromOnlineStore(ctx, groupRef.EntityKeys, groupRef.FeatureViewNames, groupRef.FeatureNames) + featureData, err := fs.readFromOnlineStore(ctx, groupRef.EntityKeys, groupRef.FeatureViewNames, groupRef.FeatureNames, requestedFeatureViews) if err != nil { return nil, err } @@ -320,9 +324,13 @@ func (fs *FeatureStore) GetFeatureView(featureViewName string, hideDummyEntity b return fv, nil } +// readFromOnlineStore reads one group of features from the online store. views is the request's own +// snapshot of its feature views (the one the entity keys were built from); stores that need entity names, +// such as Bigtable, get them from it, so a registry refresh mid-request cannot mix schemas. func (fs *FeatureStore) readFromOnlineStore(ctx context.Context, entityRows []*prototypes.EntityKey, requestedFeatureViewNames []string, requestedFeatureNames []string, + views []*onlineserving.FeatureViewAndRefs, ) ([][]onlinestore.FeatureData, error) { // Create a Datadog span from context ctx, span := tracer.Start(ctx, "fs.readFromOnlineStore") @@ -333,9 +341,23 @@ func (fs *FeatureStore) readFromOnlineStore(ctx context.Context, entityRows []*p for index, entityKey := range entityRows { entityRowsValue[index] = &prototypes.EntityKey{JoinKeys: entityKey.JoinKeys, EntityValues: entityKey.EntityValues} } + if entityAwareStore, ok := fs.onlineStore.(onlinestore.EntityAwareOnlineStore); ok { + return entityAwareStore.OnlineReadWithEntities(ctx, entityRowsValue, requestedFeatureViewNames, + requestedFeatureNames, entityNamesByView(views)) + } return fs.onlineStore.OnlineRead(ctx, entityRowsValue, requestedFeatureViewNames, requestedFeatureNames) } +// entityNamesByView maps each view's base name, which is the name GroupFeatureRefs passes to the online +// store, to its entity names. Projections of one view share a base name and its entities. +func entityNamesByView(views []*onlineserving.FeatureViewAndRefs) map[string][]string { + names := make(map[string][]string, len(views)) + for _, viewAndRefs := range views { + names[viewAndRefs.View.Base.Name] = viewAndRefs.View.EntityNames + } + return names +} + func (fs *FeatureStore) GetFcosMap() (map[string]*model.Entity, map[string]*model.FeatureView, map[string]*model.OnDemandFeatureView, error) { odfvs, err := fs.ListOnDemandFeatureViews() if err != nil { diff --git a/go/internal/feast/featurestore_bigtable_test.go b/go/internal/feast/featurestore_bigtable_test.go new file mode 100644 index 00000000000..98750ad43eb --- /dev/null +++ b/go/internal/feast/featurestore_bigtable_test.go @@ -0,0 +1,133 @@ +package feast + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "cloud.google.com/go/bigtable/bttest" + "github.com/apache/arrow/go/v17/arrow/array" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/feast-dev/feast/go/internal/feast/registry" + "github.com/feast-dev/feast/go/internal/test" + "github.com/feast-dev/feast/go/protos/feast/serving" + "github.com/feast-dev/feast/go/protos/feast/types" +) + +// TestBigtablePythonMaterializeGoRead materializes the test feature repo into an in-memory Bigtable with +// the Python SDK's `feast apply` and `feast materialize-incremental`, then reads it back through +// FeatureStore.GetOnlineFeatures and the Go Bigtable store, and checks the values and event timestamps +// against the latest parquet row of each driver. It needs the `feast` CLI with the gcp extra +// (google-cloud-bigtable) and skips without it. +func TestBigtablePythonMaterializeGoRead(t *testing.T) { + if testing.Short() { + t.Skip("runs feast apply and materialize") + } + requireFeastWithBigtable(t) + + srv, err := bttest.NewServer("localhost:0") + require.NoError(t, err) + t.Cleanup(srv.Close) + t.Setenv("BIGTABLE_EMULATOR_HOST", srv.Addr) + + repoPath := newBigtableFeatureRepo(t) + runFeast(t, repoPath, "apply") + runFeast(t, repoPath, "materialize-incremental", time.Now().UTC().Format("2006-01-02T15:04:05")) + + config, err := registry.NewRepoConfigFromFile(repoPath) + require.NoError(t, err) + fs, err := NewFeatureStore(config, nil) + require.NoError(t, err) + t.Cleanup(fs.onlineStore.Destruct) + + const missingDriver = 9999 + drivers := []int64{1001, 1002, 1003, missingDriver} + entityValues := make([]*types.Value, len(drivers)) + for i, id := range drivers { + entityValues[i] = &types.Value{Val: &types.Value_Int64Val{Int64Val: id}} + } + vectors, err := fs.GetOnlineFeatures(context.Background(), + []string{"driver_hourly_stats:conv_rate", "driver_hourly_stats:acc_rate", "driver_hourly_stats:avg_daily_trips"}, + nil, map[string]*types.RepeatedValue{"driver_id": {Val: entityValues}}, nil, false) + require.NoError(t, err) + + rows, err := test.ReadParquet(filepath.Join(featureRepoBasePath, "feature_repo", "driver_stats.parquet")) + require.NoError(t, err) + latest := test.GetLatestFeatures(rows, map[int64]bool{1001: true, 1002: true, 1003: true}) + + byName := make(map[string]int, len(vectors)) + for i, v := range vectors { + byName[v.Name] = i + } + convRate := vectors[byName["conv_rate"]] + accRate := vectors[byName["acc_rate"]] + trips := vectors[byName["avg_daily_trips"]] + for i, id := range drivers { + if id == missingDriver { + assert.Equal(t, serving.FieldStatus_NOT_FOUND, convRate.Statuses[i], "driver %d", id) + continue + } + want := latest[id] + require.NotNil(t, want, "driver %d has no parquet row", id) + assert.Equal(t, serving.FieldStatus_PRESENT, convRate.Statuses[i], "driver %d", id) + assert.Equal(t, want.ConvRate, convRate.Values.(*array.Float32).Value(i), "driver %d conv_rate", id) + assert.Equal(t, want.AccRate, accRate.Values.(*array.Float32).Value(i), "driver %d acc_rate", id) + assert.Equal(t, int64(want.AvgDailyTrips), trips.Values.(*array.Int64).Value(i), "driver %d avg_daily_trips", id) + // ReadParquet returns driver_stats.parquet's raw microsecond timestamps (it reads them as arrow.Second). + assert.Equal(t, time.UnixMicro(want.EventTimestamp).Unix(), convRate.Timestamps[i].GetSeconds(), "driver %d event_ts", id) + } +} + +// requireFeastWithBigtable skips the test unless the `feast` CLI is on PATH and the Python beside it can +// import google.cloud.bigtable (the gcp extra). +func requireFeastWithBigtable(t *testing.T) { + t.Helper() + feastPath, err := exec.LookPath("feast") + if err != nil { + t.Skip("needs the feast CLI on PATH") + } + python := filepath.Join(filepath.Dir(feastPath), "python") + if out, err := exec.Command(python, "-c", "import google.cloud.bigtable").CombinedOutput(); err != nil { + t.Skipf("needs the feast CLI with the gcp extra (google-cloud-bigtable): %v: %s", err, out) + } +} + +// newBigtableFeatureRepo copies the test feature repo's definitions and data into a temporary repo whose +// online store is Bigtable on the emulator, and returns its path. +func newBigtableFeatureRepo(t *testing.T) string { + t.Helper() + repoPath := t.TempDir() + source := filepath.Join(featureRepoBasePath, "feature_repo") + for _, name := range []string{"__init__.py", "example.py", "driver_stats.parquet"} { + data, err := os.ReadFile(filepath.Join(source, name)) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, name), data, 0o644)) + } + yaml := `project: bigtable_e2e +registry: data/registry.db +provider: local +online_store: + type: bigtable + project_id: test-project + instance: test-instance +entity_key_serialization_version: 3 +` + require.NoError(t, os.WriteFile(filepath.Join(repoPath, "feature_store.yaml"), []byte(yaml), 0o644)) + return repoPath +} + +// runFeast runs one feast CLI command in repoPath, with the test's environment (the emulator address). +func runFeast(t *testing.T, repoPath string, args ...string) { + t.Helper() + cmd := exec.Command("feast", args...) + cmd.Dir = repoPath + cmd.Env = os.Environ() + out, err := cmd.CombinedOutput() + require.NoError(t, err, fmt.Sprintf("feast %v: %s", args, out)) +} diff --git a/go/internal/feast/featurestore_test.go b/go/internal/feast/featurestore_test.go index e1f908b9062..6f9cf88fdf7 100644 --- a/go/internal/feast/featurestore_test.go +++ b/go/internal/feast/featurestore_test.go @@ -11,10 +11,15 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" + "github.com/feast-dev/feast/go/internal/feast/model" + "github.com/feast-dev/feast/go/internal/feast/onlineserving" "github.com/feast-dev/feast/go/internal/feast/onlinestore" "github.com/feast-dev/feast/go/internal/feast/registry" "github.com/feast-dev/feast/go/internal/test" + "github.com/feast-dev/feast/go/protos/feast/core" "github.com/feast-dev/feast/go/protos/feast/serving" "github.com/feast-dev/feast/go/protos/feast/types" ) @@ -240,3 +245,136 @@ func testRedisODFVNoTransformationService(t *testing.T, fs *FeatureStore) { assert.ErrorAs(t, err, &FeastTransformationServiceNotConfigured{}) } + +// entityAwareFakeStore implements both OnlineStore and EntityAwareOnlineStore and records +// which read method the feature store called, and with which entity names. +type entityAwareFakeStore struct { + plainReads int + entityNamesByView []map[string][]string +} + +var _ onlinestore.OnlineStore = (*entityAwareFakeStore)(nil) +var _ onlinestore.EntityAwareOnlineStore = (*entityAwareFakeStore)(nil) + +func (s *entityAwareFakeStore) Destruct() {} + +func (s *entityAwareFakeStore) OnlineRead(_ context.Context, entityKeys []*types.EntityKey, + _ []string, _ []string) ([][]onlinestore.FeatureData, error) { + s.plainReads++ + return make([][]onlinestore.FeatureData, len(entityKeys)), nil +} + +func (s *entityAwareFakeStore) OnlineReadWithEntities(_ context.Context, entityKeys []*types.EntityKey, + _ []string, _ []string, entityNamesByView map[string][]string) ([][]onlinestore.FeatureData, error) { + s.entityNamesByView = append(s.entityNamesByView, entityNamesByView) + return make([][]onlinestore.FeatureData, len(entityKeys)), nil +} + +func viewAndRefs(name string, entityNames []string, featureRefs ...string) *onlineserving.FeatureViewAndRefs { + return &onlineserving.FeatureViewAndRefs{ + View: &model.FeatureView{Base: model.NewBaseFeatureView(name, nil), EntityNames: entityNames}, + FeatureRefs: featureRefs, + } +} + +func int64EntityKey(joinKey string, value int64) *types.EntityKey { + return &types.EntityKey{ + JoinKeys: []string{joinKey}, + EntityValues: []*types.Value{{Val: &types.Value_Int64Val{Int64Val: value}}}, + } +} + +func TestReadFromOnlineStoreUsesEntityAwareStore(t *testing.T) { + store := &entityAwareFakeStore{} + fs := &FeatureStore{onlineStore: store} + // A second, aliased projection of fvA keeps the base name and the entities; the map keys on Base.Name. + aliasedA := viewAndRefs("fvA", []string{"subscriber"}, "f3") + aliasedA.View.Base.Projection = &model.FeatureViewProjection{Name: "fvA", NameAlias: "fvA_alias"} + views := []*onlineserving.FeatureViewAndRefs{ + viewAndRefs("fvA", []string{"subscriber"}, "f1"), + viewAndRefs("fvB", []string{"household"}, "f2"), + aliasedA, + // An entityless view carries the dummy entity, which the store needs to find its table. + viewAndRefs("fvNoEntity", []string{model.DUMMY_ENTITY_NAME}, "f4"), + } + keys := []*types.EntityKey{int64EntityKey("user_profile_id", 1)} + + rows, err := fs.readFromOnlineStore(context.Background(), keys, + []string{"fvA", "fvB", "fvA", "fvNoEntity"}, []string{"f1", "f2", "f3", "f4"}, views) + + require.NoError(t, err) + assert.Len(t, rows, 1) + assert.Zero(t, store.plainReads) + assert.Equal(t, []map[string][]string{ + {"fvA": {"subscriber"}, "fvB": {"household"}, "fvNoEntity": {"__dummy"}}, + }, store.entityNamesByView) +} + +func TestReadFromOnlineStorePlainStoreUnchanged(t *testing.T) { + store := new(MockRedis) + fs := &FeatureStore{onlineStore: store} + views := []*onlineserving.FeatureViewAndRefs{viewAndRefs("fvA", []string{"subscriber"}, "f1")} + keys := []*types.EntityKey{int64EntityKey("user_profile_id", 1)} + want := [][]onlinestore.FeatureData{{{ + Reference: serving.FeatureReferenceV2{FeatureViewName: "fvA", FeatureName: "f1"}, + Value: types.Value{Val: &types.Value_Int64Val{Int64Val: 7}}, + }}} + store.On("OnlineRead", mock.Anything, keys, []string{"fvA"}, []string{"f1"}).Return(want, nil) + + rows, err := fs.readFromOnlineStore(context.Background(), keys, []string{"fvA"}, []string{"f1"}, views) + + require.NoError(t, err) + assert.Equal(t, want, rows) + store.AssertExpectations(t) +} + +// writeRegistryFile serialises a registry proto to a file the file registry store can load. +func writeRegistryFile(t *testing.T, registryProto *core.Registry) string { + t.Helper() + path := filepath.Join(t.TempDir(), "registry.db") + data, err := proto.Marshal(registryProto) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data, 0o644)) + return path +} + +func TestStreamViewWinsForEntityAwareStore(t *testing.T) { + const project = "stream_wins" + features := []*core.FeatureSpecV2{{Name: "f1", ValueType: types.ValueType_INT64}} + registryPath := writeRegistryFile(t, &core.Registry{ + RegistrySchemaVersion: registry.REGISTRY_SCHEMA_VERSION, + Entities: []*core.Entity{ + {Spec: &core.EntitySpecV2{Name: "subscriber", Project: project, JoinKey: "user_profile_id"}}, + {Spec: &core.EntitySpecV2{Name: "household", Project: project, JoinKey: "household_id"}}, + }, + FeatureViews: []*core.FeatureView{{Spec: &core.FeatureViewSpec{ + Name: "fv", Project: project, Entities: []string{"household"}, Features: features, + Ttl: &durationpb.Duration{}, + }}}, + StreamFeatureViews: []*core.StreamFeatureView{{Spec: &core.StreamFeatureViewSpec{ + Name: "fv", Project: project, Entities: []string{"subscriber"}, Features: features, + Ttl: &durationpb.Duration{}, + }}}, + }) + fs, err := NewFeatureStore(®istry.RepoConfig{ + Project: project, + // A zero TTL loads the registry once with no periodic refresh. + Registry: map[string]interface{}{"path": registryPath, "cache_ttl_seconds": 0}, + Provider: "local", + OnlineStore: map[string]interface{}{"type": "redis", "connection_string": "localhost:6379"}, + }, nil) + require.NoError(t, err) + fs.onlineStore.Destruct() + store := &entityAwareFakeStore{} + fs.onlineStore = store + entities := map[string]*types.RepeatedValue{ + "user_profile_id": {Val: []*types.Value{{Val: &types.Value_Int64Val{Int64Val: 1}}}}, + } + + _, err = fs.GetOnlineFeatures(context.Background(), []string{"fv:f1"}, nil, entities, + map[string]*types.RepeatedValue{}, true) + + require.NoError(t, err) + assert.Zero(t, store.plainReads) + assert.Equal(t, []map[string][]string{{"fv": {"subscriber"}}}, store.entityNamesByView) +} diff --git a/go/internal/feast/onlinestore/bigtableconfig.go b/go/internal/feast/onlinestore/bigtableconfig.go new file mode 100644 index 00000000000..b1eb13ae86f --- /dev/null +++ b/go/internal/feast/onlinestore/bigtableconfig.go @@ -0,0 +1,181 @@ +package onlinestore + +// Parsing and validation of the Bigtable online store's online_store config. + +import ( + "errors" + "fmt" + "math" + "time" +) + +// bigtableConfig is the parsed online_store section of feature_store.yaml. MaxInflightReads is zero, no +// limit, only when max_inflight_reads is unset (the key itself must be positive); a zero MaxInflightWait +// rejects a read at once when max_inflight_reads is full. +type bigtableConfig struct { + ProjectID, Instance, AppProfile string + KeysPerRequest, MaxConcurrentChunks, MaxInflightReads int + ReadTimeout, MaxInflightWait time.Duration + AdaptiveChunking, DisableMetrics bool +} + +// parseBigtableConfig reads the online_store config map and applies defaults; validate checks the ranges. +// Numbers must be whole and positive (YAML gives float64), switches must be YAML booleans, a null keeps the +// default as in Python, and unknown keys are ignored. +func parseBigtableConfig(m map[string]interface{}) (bigtableConfig, error) { + cfg := bigtableConfig{ + KeysPerRequest: bigtableDefaultKeysPerRequest, + MaxConcurrentChunks: bigtableDefaultMaxConcurrentChunks, + } + if err := parseBigtableStrings(m, &cfg); err != nil { + return bigtableConfig{}, err + } + if err := parseBigtableInts(m, &cfg); err != nil { + return bigtableConfig{}, err + } + for _, f := range []struct { + key string + dst *bool + }{ + {"adaptive_chunking", &cfg.AdaptiveChunking}, + {"disable_metrics", &cfg.DisableMetrics}, + } { + if err := optionalBool(m, f.key, f.dst); err != nil { + return bigtableConfig{}, err + } + } + return cfg, nil +} + +// validate fails unless keys_per_request is 1 to bigtableMaxKeysPerRequest (this store's cap per ReadRows, +// which adaptive_chunking grows to), max_concurrent_chunks and read_timeout_ms are positive, and +// max_inflight_reads and max_inflight_wait_ms are not negative. +func (cfg bigtableConfig) validate() error { + if cfg.KeysPerRequest < 1 || cfg.KeysPerRequest > bigtableMaxKeysPerRequest { + return fmt.Errorf("bigtable online store: keys_per_request must be between 1 and %d, got %d", + bigtableMaxKeysPerRequest, cfg.KeysPerRequest) + } + if cfg.MaxConcurrentChunks < 1 { + return fmt.Errorf("bigtable online store: max_concurrent_chunks must be positive, got %d", cfg.MaxConcurrentChunks) + } + if cfg.ReadTimeout <= 0 { + return fmt.Errorf("bigtable online store: read_timeout_ms must be positive, got %d", cfg.ReadTimeout.Milliseconds()) + } + if cfg.MaxInflightReads < 0 { + return fmt.Errorf("bigtable online store: max_inflight_reads must not be negative, got %d", cfg.MaxInflightReads) + } + if cfg.MaxInflightWait < 0 { + return fmt.Errorf("bigtable online store: max_inflight_wait_ms must not be negative, got %d", + cfg.MaxInflightWait.Milliseconds()) + } + return nil +} + +func parseBigtableStrings(m map[string]interface{}, cfg *bigtableConfig) error { + for _, f := range []struct { + key string + dst *string + }{ + {"instance", &cfg.Instance}, + {"project_id", &cfg.ProjectID}, + {"app_profile", &cfg.AppProfile}, + } { + if err := optionalString(m, f.key, f.dst); err != nil { + return err + } + } + if cfg.Instance == "" { + return errors.New("bigtable online store: instance is required") + } + return nil +} + +// parseBigtableInts reads the numeric keys. max_versions is Python's GC rule; this reader takes the latest +// cell whatever it is, so it is not read. +func parseBigtableInts(m map[string]interface{}, cfg *bigtableConfig) error { + readTimeoutMs := int(bigtableDefaultReadTimeout.Milliseconds()) + for _, f := range []struct { + key string + dst *int + }{ + {"keys_per_request", &cfg.KeysPerRequest}, + {"max_concurrent_chunks", &cfg.MaxConcurrentChunks}, + {"read_timeout_ms", &readTimeoutMs}, + {"max_inflight_reads", &cfg.MaxInflightReads}, + } { + if err := optionalPositiveInt(m, f.key, f.dst); err != nil { + return err + } + } + cfg.ReadTimeout = time.Duration(readTimeoutMs) * time.Millisecond + inflightWaitMs, err := optionalNonNegativeInt(m, "max_inflight_wait_ms") + if err != nil { + return err + } + cfg.MaxInflightWait = time.Duration(inflightWaitMs) * time.Millisecond + return nil +} + +// optionalString sets *dst to a present, non-null string m[key]; a null (`key:`, or an unset ${VAR}) keeps it. +func optionalString(m map[string]interface{}, key string, dst *string) error { + raw := m[key] + if raw == nil { + return nil + } + s, ok := raw.(string) + if !ok { + return fmt.Errorf("bigtable online store: %s must be a string, got %T", key, raw) + } + *dst = s + return nil +} + +// optionalBool sets *dst to a present, non-null bool m[key]. +func optionalBool(m map[string]interface{}, key string, dst *bool) error { + raw := m[key] + if raw == nil { + return nil + } + b, ok := raw.(bool) + if !ok { + return fmt.Errorf("bigtable online store: %s must be true or false, got %T %v", key, raw, raw) + } + *dst = b + return nil +} + +// optionalPositiveInt sets *dst to a present, non-null m[key] that is a whole number from 1 to MaxInt32. +func optionalPositiveInt(m map[string]interface{}, key string, dst *int) error { + return optionalWholeNumber(m, key, dst, 1, "a positive integer") +} + +// optionalNonNegativeInt returns m[key] when it is a whole number from 0 to MaxInt32, and 0 when it is +// absent or null. +func optionalNonNegativeInt(m map[string]interface{}, key string) (int, error) { + var n int + err := optionalWholeNumber(m, key, &n, 0, "a non-negative integer") + return n, err +} + +// optionalWholeNumber sets *dst to a present, non-null m[key] that is a whole number from lowest to +// MaxInt32; want names the accepted range in the error. +func optionalWholeNumber(m map[string]interface{}, key string, dst *int, lowest float64, want string) error { + raw := m[key] + if raw == nil { + return nil + } + var f float64 + switch v := raw.(type) { + case float64: + f = v + case int: + f = float64(v) + default: + return fmt.Errorf("bigtable online store: %s must be %s, got %T %v", key, want, raw, raw) + } + if f != math.Trunc(f) || f < lowest || f > math.MaxInt32 { + return fmt.Errorf("bigtable online store: %s must be %s, got %v", key, want, raw) + } + *dst = int(f) + return nil +} diff --git a/go/internal/feast/onlinestore/bigtableonlinestore.go b/go/internal/feast/onlinestore/bigtableonlinestore.go new file mode 100644 index 00000000000..da7bf1eeeda --- /dev/null +++ b/go/internal/feast/onlinestore/bigtableonlinestore.go @@ -0,0 +1,936 @@ +package onlinestore + +// Bigtable online store for the Go feature server. It reads what the Python BigtableOnlineStore +// (sdk/python/feast/infra/online_stores/bigtable.py) writes, so table names, row keys and the event_ts +// encoding must match Python exactly. + +import ( + "context" + "crypto/md5" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "os" + "regexp" + "slices" + "sort" + "strings" + "sync" + "time" + + "cloud.google.com/go/bigtable" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/rs/zerolog/log" + "github.com/spaolacci/murmur3" + "go.opentelemetry.io/otel/attribute" + otelcodes "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" + "golang.org/x/oauth2/google" + "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" + "google.golang.org/api/option" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/feast-dev/feast/go/internal/feast/model" + "github.com/feast-dev/feast/go/internal/feast/registry" + "github.com/feast-dev/feast/go/protos/feast/serving" + "github.com/feast-dev/feast/go/protos/feast/types" +) + +const ( + // In benchmarks, a ReadRows of many row keys took longer than the same keys sent as several small + // ReadRows in parallel, so the defaults favor many small requests in parallel. They wait on Bigtable + // rather than CPU, so concurrency is not tied to GOMAXPROCS. + bigtableDefaultKeysPerRequest = 5 + bigtableDefaultMaxConcurrentChunks = 50 + bigtableMaxKeysPerRequest = 100 + + // bigtableDefaultReadTimeout bounds a whole read call when read_timeout_ms is unset. Without a deadline + // the Go client retries some errors indefinitely. 60 s is a generous ceiling, not a latency target. + bigtableDefaultReadTimeout = 60 * time.Second + + // Table name limits, as in Python's BigtableOnlineStore._get_table_name. + bigtableTableNameMaxLength = 50 + bigtableEntitiesPartMaxLength = 24 + bigtableProjectReadableLength = 10 + + // bigtableSerializationVersion is the only entity key serialization version the Bigtable store reads. + bigtableSerializationVersion = 3 + + // naiveISOLayout is datetime.isoformat() of a datetime without a timezone, read as UTC. + naiveISOLayout = "2006-01-02T15:04:05.999999999" + // secondsOffsetISOLayout is datetime.isoformat() with a seconds UTC offset (+05:53:28), which RFC 3339 + // cannot express. + secondsOffsetISOLayout = "2006-01-02T15:04:05.999999999-07:00:00" + + // bigtableFeatureFamily is the column family Python writes every cell to. + bigtableFeatureFamily = "features" + // bigtableEventTSQualifier is the qualifier of a row's event timestamp. + bigtableEventTSQualifier = "event_ts" + + // bigtableStartupTimeout bounds the store's own PingAndWarm call after the client is built. + bigtableStartupTimeout = 10 * time.Second +) + +// bigtableReadRejectedError is the error of a read that max_inflight_reads turned away because the server +// was at its cap. Its gRPC status is RESOURCE_EXHAUSTED, so the gRPC feature server returns that code and +// a client can back off or retry on another replica. +type bigtableReadRejectedError struct{ msg string } + +func (e *bigtableReadRejectedError) Error() string { return e.msg } + +// GRPCStatus gives the error the RESOURCE_EXHAUSTED code; status.FromError finds it through wrapping too. +func (e *bigtableReadRejectedError) GRPCStatus() *status.Status { + return status.New(codes.ResourceExhausted, e.msg) +} + +// Prometheus metrics of online reads, served on the feature server's metrics port. A vector exports +// nothing until a read records into it, so other stores' deployments see no Bigtable series. +var ( + bigtableReadDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "feast", + Subsystem: "bigtable", + Name: "online_read_duration_seconds", + Help: "Time taken by one Bigtable online read call, including waits for slots, by status (ok, error or rejected).", + Buckets: []float64{.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}, + }, []string{"status"}) + bigtableReadChunks = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "feast", + Subsystem: "bigtable", + Name: "online_read_chunks_total", + Help: "ReadRows calls sent by Bigtable online reads.", + }, []string{"table"}) + bigtableReadRowsFound = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "feast", + Subsystem: "bigtable", + Name: "online_read_rows_found_total", + Help: "Rows returned by Bigtable online reads.", + }, []string{"table"}) +) + +// BigtableOnlineStore reads features that the Python BigtableOnlineStore wrote. Tables are named after +// each feature view's entities, so reads go through OnlineReadWithEntities (EntityAwareOnlineStore). +type BigtableOnlineStore struct { + project string // Feast project, the first part of every table name + cfg bigtableConfig + serializationVersion int64 + client *bigtable.Client + tables sync.Map // table name -> *bigtable.Table + closeOnce sync.Once + // inflight holds the max_inflight_reads slots that admitted reads reserve; nil is unlimited. + inflight *semaphore.Weighted +} + +var ( + _ OnlineStore = (*BigtableOnlineStore)(nil) + _ EntityAwareOnlineStore = (*BigtableOnlineStore)(nil) +) + +// NewBigtableOnlineStore builds the store from the online_store section of feature_store.yaml. An unset +// project_id falls back to GOOGLE_CLOUD_PROJECT, GCLOUD_PROJECT, then the default credentials' project. +// +// Outside the emulator the client primes its connections with PingAndWarm when it is created (three +// attempts each), so bad credentials or an unreachable instance fail client construction. The store then +// pings once more: that gives the emulator and pre-dialed connections, which skip priming, the same check, +// and it logs a warning for NotFound, which the client's priming treats as success and logs only at debug +// level (see tolerableStartupPingError). +func NewBigtableOnlineStore(project string, config *registry.RepoConfig, onlineStoreConfig map[string]interface{}) (*BigtableOnlineStore, error) { + cfg, err := parseBigtableConfig(onlineStoreConfig) + if err != nil { + return nil, err + } + ctx := context.Background() + if cfg.ProjectID, err = resolveProjectID(ctx, cfg.ProjectID, defaultCredentialsProjectID); err != nil { + return nil, err + } + return newBigtableOnlineStore(ctx, project, config, cfg, bigtableStartupTimeout) +} + +// newBigtableOnlineStore validates cfg, builds the client for an already resolved project and warms it +// under startupTimeout. Tests pass opts to dial bttest. +func newBigtableOnlineStore(ctx context.Context, project string, config *registry.RepoConfig, cfg bigtableConfig, + startupTimeout time.Duration, opts ...option.ClientOption) (*BigtableOnlineStore, error) { + if err := cfg.validate(); err != nil { + return nil, err + } + version, err := normalizeSerializationVersion(config.EntityKeySerializationVersion) + if err != nil { + return nil, err + } + client, err := bigtable.NewClientWithConfig(ctx, cfg.ProjectID, cfg.Instance, bigtableClientConfig(cfg), opts...) + if err != nil { + return nil, fmt.Errorf("bigtable online store: create client for projects/%s/instances/%s: %w", + cfg.ProjectID, cfg.Instance, err) + } + pingCtx, cancel := context.WithTimeout(ctx, startupTimeout) + defer cancel() + if err := client.PingAndWarm(pingCtx); err != nil { + reason, ok := tolerableStartupPingError(err, os.Getenv("BIGTABLE_EMULATOR_HOST") != "") + if !ok { + // The ping error is the one to return; a Close error on a client that never served adds nothing. + _ = client.Close() + return nil, fmt.Errorf("bigtable online store: PingAndWarm projects/%s/instances/%s: %w", + cfg.ProjectID, cfg.Instance, err) + } + log.Warn().Err(err). + Str("project_id", cfg.ProjectID). + Str("instance", cfg.Instance). + Msgf("Bigtable PingAndWarm failed, starting anyway: %s", reason) + } + log.Info(). + Str("project_id", cfg.ProjectID). + Str("instance", cfg.Instance). + Str("app_profile", appProfileForLog(cfg.AppProfile)). + Int64("entity_key_serialization_version", version). + Str("metrics", bigtableMetricsMode(cfg)). + Int("keys_per_request", cfg.KeysPerRequest). + Int("max_concurrent_chunks", cfg.MaxConcurrentChunks). + Bool("adaptive_chunking", cfg.AdaptiveChunking). + Int("max_inflight_reads", cfg.MaxInflightReads). + Int64("max_inflight_wait_ms", cfg.MaxInflightWait.Milliseconds()). + Int64("read_timeout_ms", cfg.ReadTimeout.Milliseconds()). + Msg("Using Bigtable online store") + store := &BigtableOnlineStore{project: project, cfg: cfg, serializationVersion: version, client: client} + if cfg.MaxInflightReads > 0 { + store.inflight = semaphore.NewWeighted(int64(cfg.MaxInflightReads)) + } + return store, nil +} + +// bigtableClientConfig keeps the client library's defaults apart from the app profile and, with +// disable_metrics, the no-op metrics provider (no Cloud Monitoring export, so no monitoring permission). +func bigtableClientConfig(cfg bigtableConfig) bigtable.ClientConfig { + config := bigtable.ClientConfig{AppProfile: cfg.AppProfile} + if cfg.DisableMetrics { + config.MetricsProvider = bigtable.NoopMetricsProvider{} + } + return config +} + +// tolerableStartupPingError reports whether the store may start despite err from the startup PingAndWarm, +// and why. Bigtable returns NotFound for an instance with no tables yet, so failing on it would crash-loop +// a server started before the first `feast apply`; the client library treats it as a successful prime too. +// Emulators older than cloud.google.com/go/bigtable v1.15.0 return Unimplemented. Anything else fails. +func tolerableStartupPingError(err error, emulator bool) (reason string, ok bool) { + switch status.Code(err) { + case codes.NotFound: + return "the instance has no tables yet, or the instance or app profile does not exist; " + + "reads fail until both exist", true + case codes.Unimplemented: + if emulator { + return "the Bigtable emulator does not implement PingAndWarm", true + } + } + return "", false +} + +// bigtableProjectEnvVars are the environment variables Python's google.auth.default reads for the project, +// in its order, before the credentials' own project. +var bigtableProjectEnvVars = []string{"GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT"} + +// resolveProjectID returns configured when set, then the first non-empty bigtableProjectEnvVars value, and +// otherwise the project that find reports (the default credentials' project in production). Tests pass +// their own find, so they never look up credentials. +func resolveProjectID(ctx context.Context, configured string, find func(context.Context) (string, error)) (string, error) { + if configured != "" { + return configured, nil + } + for _, name := range bigtableProjectEnvVars { + if v := os.Getenv(name); v != "" { + return v, nil + } + } + found, err := find(ctx) + if err != nil { + return "", fmt.Errorf("bigtable online store: project_id is not set and default credentials failed: %w", err) + } + if found == "" { + return "", errors.New("bigtable online store: project_id is not set, GOOGLE_CLOUD_PROJECT and " + + "GCLOUD_PROJECT are empty, and the default credentials name no project") + } + return found, nil +} + +func defaultCredentialsProjectID(ctx context.Context) (string, error) { + creds, err := google.FindDefaultCredentials(ctx, bigtable.Scope) + if err != nil { + return "", err + } + return creds.ProjectID, nil +} + +func appProfileForLog(profile string) string { + if profile == "" { + return "default" + } + return profile +} + +// bigtableMetricsMode names the client's metrics setting for the startup log; the client turns metrics off +// itself for the emulator. +func bigtableMetricsMode(cfg bigtableConfig) string { + if cfg.DisableMetrics { + return "disabled (disable_metrics)" + } + if os.Getenv("BIGTABLE_EMULATOR_HOST") != "" { + return "disabled (emulator)" + } + return "default" +} + +// OnlineRead is unsupported: the store needs each feature view's entity names to find its table. The +// feature server calls OnlineReadWithEntities (EntityAwareOnlineStore) instead, so it never reaches this. +func (s *BigtableOnlineStore) OnlineRead(context.Context, []*types.EntityKey, []string, []string) ([][]FeatureData, error) { + return nil, fmt.Errorf("bigtable online store: OnlineRead needs each feature view's entity names, "+ + "use OnlineReadWithEntities: %w", errors.ErrUnsupported) +} + +// OnlineReadWithEntities reads featureNames[i] of featureViewNames[i] for every entity key and returns +// what the Python store returns for the same rows. entityNamesByView names each view's table. +// +// The result has one row per entity key and one slot per requested feature, both in input order. An +// entity with no row in any requested view gets a nil row. A view row absent beside a present one gives +// NullVal slots with a zero timestamp; a feature absent from a present row gives NullVal with the row's +// event_ts. A corrupt cell or a missing event_ts fails the whole read. +// +// read_timeout_ms bounds the whole call, including waits for slots; the caller's deadline still applies. +// A deadline or cancellation error wraps context.DeadlineExceeded or context.Canceled. +func (s *BigtableOnlineStore) OnlineReadWithEntities(ctx context.Context, entityKeys []*types.EntityKey, + featureViewNames []string, featureNames []string, entityNamesByView map[string][]string) (rows [][]FeatureData, err error) { + ctx, span := tracer.Start(ctx, "bigtable.OnlineRead") + stats := &bigtableReadStats{entities: len(entityKeys), start: time.Now()} + defer func() { stats.end(span, err) }() + ctx, cancel := s.withReadTimeout(ctx) + defer cancel() + + if len(featureViewNames) != len(featureNames) { + return nil, fmt.Errorf("bigtable online store: featureViewNames has %d entries but featureNames has %d", + len(featureViewNames), len(featureNames)) + } + plan, err := planBigtableRead(s.project, featureViewNames, featureNames, entityNamesByView) + if err != nil { + return nil, err + } + stats.tables = plan.tables + if len(entityKeys) == 0 || len(featureNames) == 0 { + return make([][]FeatureData, len(entityKeys)), nil + } + hashes, err := s.entityHashes(entityKeys) + if err != nil { + return nil, err + } + result := newBigtableReadResult(len(entityKeys), len(featureNames), len(plan.views)) + chunks := s.planChunks(plan.tables, hashes, stats) + if err := s.readChunks(ctx, chunks, result, stats); err != nil { + return nil, err + } + return result.applyMissingData(plan.views), nil +} + +// withReadTimeout bounds ctx by read_timeout_ms; when that budget fires, context.Cause names it. +func (s *BigtableOnlineStore) withReadTimeout(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeoutCause(ctx, s.cfg.ReadTimeout, fmt.Errorf("bigtable online store: read_timeout_ms %d exceeded: %w", + s.cfg.ReadTimeout.Milliseconds(), context.DeadlineExceeded)) +} + +// bigtableReadStats feed a call's span and metrics; fields not reached before an error stay zero. +// inflightWait is the time the call waited for admission to max_inflight_reads; callSlotWait sums, over its +// chunks, the time spent waiting for one of the call's own slots. Together they separate queueing from +// Bigtable time. rounds is planned, not observed: the chunk count divided by the call's slots, rounded up. +type bigtableReadStats struct { + start time.Time + tables []*bigtableTableRead + planned []*bigtableChunk + entities, rowKeys, chunkSize, chunks, rounds, rowsFound int + callSlotWait, inflightWait time.Duration +} + +// end records the call's metrics, sets the span's attributes and ends the span. +func (st *bigtableReadStats) end(span trace.Span, err error) { + outcome := "ok" + switch { + case errors.As(err, new(*bigtableReadRejectedError)): + outcome = "rejected" + case err != nil: + outcome = "error" + } + bigtableReadDuration.WithLabelValues(outcome).Observe(time.Since(st.start).Seconds()) + st.recordTableCounters() + if span.IsRecording() { + names := make([]string, len(st.tables)) + for i, tbl := range st.tables { + names[i] = tbl.name + } + span.SetAttributes( + attribute.String("bigtable.table", strings.Join(names, ",")), + attribute.Int("feast.entity_count", st.entities), + attribute.Int("bigtable.row_keys", st.rowKeys), + attribute.Int("bigtable.chunk_size", st.chunkSize), + attribute.Int("bigtable.chunks", st.chunks), + attribute.Int("bigtable.chunk_rounds", st.rounds), + attribute.Float64("bigtable.call_slot_wait_ms", float64(st.callSlotWait.Microseconds())/1000), + attribute.Float64("bigtable.inflight_wait_ms", float64(st.inflightWait.Microseconds())/1000), + attribute.Int("bigtable.rows_found", st.rowsFound), + ) + if err != nil { + span.RecordError(err) + span.SetStatus(otelcodes.Error, err.Error()) + } + } + span.End() +} + +// recordTableCounters adds each table's sent chunks and found rows to the counters, one update per table. +// planChunks keeps a table's chunks together, and readChunks has waited for them all. +func (st *bigtableReadStats) recordTableCounters() { + for i := 0; i < len(st.planned); { + table := st.planned[i].tableName + sent, rows := 0, 0 + for ; i < len(st.planned) && st.planned[i].tableName == table; i++ { + if st.planned[i].dispatched { + sent++ + rows += st.planned[i].rowsFound + } + } + if sent > 0 { + bigtableReadChunks.WithLabelValues(table).Add(float64(sent)) + bigtableReadRowsFound.WithLabelValues(table).Add(float64(rows)) + } + } +} + +// bigtableFeatureSlot is one requested feature of a view and its position in every output row. +type bigtableFeatureSlot struct { + name string + index int +} + +// bigtableViewRead is one requested feature view: its features in request order (slots), each name's +// output positions (two when requested twice), and its index into the found flags (order). +type bigtableViewRead struct { + name string + order int + slots []bigtableFeatureSlot + positions map[string][]int +} + +// bigtableTableRead is one Bigtable table and the requested views stored in it. +type bigtableTableRead struct { + name string + views []*bigtableViewRead +} + +// bigtableReadPlan is a request grouped by view (in first-seen order) and by table. +type bigtableReadPlan struct { + views []*bigtableViewRead + tables []*bigtableTableRead +} + +// planBigtableRead groups the requested features by view, then the views by table. +func planBigtableRead(project string, featureViewNames, featureNames []string, + entityNamesByView map[string][]string) (*bigtableReadPlan, error) { + plan := &bigtableReadPlan{views: groupBigtableFeaturesByView(featureViewNames, featureNames)} + byName := make(map[string]*bigtableTableRead) + for _, view := range plan.views { + entityNames, ok := entityNamesByView[view.name] + if !ok { + return nil, fmt.Errorf("bigtable online store: no entity names for feature view %s", view.name) + } + name := bigtableTableName(project, entityNames) + tbl, ok := byName[name] + if !ok { + tbl = &bigtableTableRead{name: name} + byName[name] = tbl + plan.tables = append(plan.tables, tbl) + } + tbl.views = append(tbl.views, view) + } + return plan, nil +} + +// groupBigtableFeaturesByView pairs featureViewNames[i] with featureNames[i] and output position i. +func groupBigtableFeaturesByView(featureViewNames, featureNames []string) []*bigtableViewRead { + byName := make(map[string]*bigtableViewRead) + var views []*bigtableViewRead + for i, viewName := range featureViewNames { + view, ok := byName[viewName] + if !ok { + view = &bigtableViewRead{name: viewName, order: len(views), positions: make(map[string][]int)} + byName[viewName] = view + views = append(views, view) + } + feature := featureNames[i] + view.slots = append(view.slots, bigtableFeatureSlot{name: feature, index: i}) + view.positions[feature] = append(view.positions[feature], i) + } + return views +} + +// qualifierPattern matches the requested qualifiers of the table's views plus event_ts. Python builds the +// same pattern but does not escape names, so a name with regex metacharacters matches more there. +func (t *bigtableTableRead) qualifierPattern() string { + seen := make(map[string]bool) + var names []string + for _, view := range t.views { + for name := range view.positions { + if !seen[name] { + seen[name] = true + names = append(names, regexp.QuoteMeta(name)) + } + } + } + sort.Strings(names) + return "^(" + strings.Join(append(names, bigtableEventTSQualifier), "|") + ")$" +} + +// readFilter keeps the requested qualifiers and event_ts, newest cell only. Keep LatestNFilter(1): without +// it a read returns older cell versions whenever max_versions is above 1, and Bigtable's in-memory tier +// never serves those, so every read would go to storage (TestBigtableReadFilterKeepsNewestCellOnly). +func (t *bigtableTableRead) readFilter() bigtable.Filter { + return bigtable.ChainFilters(bigtable.ColumnFilter(t.qualifierPattern()), bigtable.LatestNFilter(1)) +} + +// entityHashes returns the row-key hash of every entity key, in input order. +func (s *BigtableOnlineStore) entityHashes(entityKeys []*types.EntityKey) ([]string, error) { + hashes := make([]string, len(entityKeys)) + for i, key := range entityKeys { + hash, err := bigtableEntityHash(key, s.serializationVersion) + if err != nil { + return nil, fmt.Errorf("bigtable online store: serialize entity key %d: %w", i, err) + } + hashes[i] = hash + } + return hashes, nil +} + +// bigtableRowTarget is the view of a row key and the entity positions that produced it (several when an +// entity key is repeated). +type bigtableRowTarget struct { + view *bigtableViewRead + entities []int +} + +// rowTargets builds one row key per unique entity per view of the table, in first-seen order. +func (t *bigtableTableRead) rowTargets(hashes []string) (map[string]*bigtableRowTarget, bigtable.RowList) { + targets := make(map[string]*bigtableRowTarget, len(hashes)*len(t.views)) + keys := make(bigtable.RowList, 0, len(hashes)*len(t.views)) + for _, view := range t.views { + for i, hash := range hashes { + key := bigtableRowKeyFromHash(hash, view.name) + if target, ok := targets[key]; ok { + target.entities = append(target.entities, i) + continue + } + targets[key] = &bigtableRowTarget{view: view, entities: []int{i}} + keys = append(keys, key) + } + } + return targets, keys +} + +// bigtableReadResult is the preallocated output, plus a found flag per (entity, view) at +// entity*numViews + view.order. +type bigtableReadResult struct { + rows [][]FeatureData + found []bool + numViews int +} + +func newBigtableReadResult(numEntities, numFeatures, numViews int) *bigtableReadResult { + rows := make([][]FeatureData, numEntities) + for i := range rows { + rows[i] = make([]FeatureData, numFeatures) + } + return &bigtableReadResult{rows: rows, found: make([]bool, numEntities*numViews), numViews: numViews} +} + +// bigtableChunk is the row keys of one table read with one ReadRows. dispatched (set just before the +// ReadRows is sent) and rowsFound are written only by the chunk's goroutine, and read only after readChunks' +// group.Wait. +type bigtableChunk struct { + tableName string + table *bigtable.Table + targets map[string]*bigtableRowTarget // shared by the table's chunks, read-only once built + keys bigtable.RowList + filter bigtable.ReadOption + dispatched bool + rowsFound int +} + +// planChunks builds every table's row keys and cuts each table's keys into chunks of bigtableChunkSize. +func (s *BigtableOnlineStore) planChunks(tables []*bigtableTableRead, hashes []string, stats *bigtableReadStats) []*bigtableChunk { + type tableKeys struct { + tbl *bigtableTableRead + targets map[string]*bigtableRowTarget + keys bigtable.RowList + } + built := make([]tableKeys, len(tables)) + for i, tbl := range tables { + targets, keys := tbl.rowTargets(hashes) + built[i] = tableKeys{tbl: tbl, targets: targets, keys: keys} + stats.rowKeys += len(keys) + } + size := bigtableChunkSize(s.cfg, stats.rowKeys) + stats.chunkSize = size + var chunks []*bigtableChunk + for _, b := range built { + handle, filter := s.table(b.tbl.name), bigtable.RowFilter(b.tbl.readFilter()) + for part := range slices.Chunk(b.keys, size) { + chunks = append(chunks, &bigtableChunk{tableName: b.tbl.name, table: handle, targets: b.targets, keys: part, filter: filter}) + } + } + stats.chunks = len(chunks) + stats.planned = chunks + return chunks +} + +// bigtableChunkSize is the row keys per ReadRows for a call of rowKeys keys: keys_per_request, or with +// adaptive_chunking the smallest size from keys_per_request up to 100 that sends the call in one round of +// max_concurrent_chunks. Each table is cut separately, so a call over several tables may plan a few +// chunks more than one round; those wait for a slot. +func bigtableChunkSize(cfg bigtableConfig, rowKeys int) int { + if !cfg.AdaptiveChunking { + return cfg.KeysPerRequest + } + // Ceiling division without rowKeys+MaxConcurrentChunks-1, which could overflow a 32-bit int. + size := rowKeys / cfg.MaxConcurrentChunks + if rowKeys%cfg.MaxConcurrentChunks != 0 { + size++ + } + return min(max(size, cfg.KeysPerRequest), bigtableMaxKeysPerRequest) +} + +// readChunks reads the chunks with up to slots of them in flight, where slots is the smallest of the chunk +// count, max_concurrent_chunks and max_inflight_reads. With max_inflight_reads set, the call reserves all +// its slots before it sends any chunk and holds them until it ends, so a server at its cap rejects whole +// reads rather than cancelling chunks it has already sent. A slot is taken before a chunk's goroutine +// starts, so a chunk waiting for one holds no goroutine. The first error cancels the rest. Chunks write +// result without locks: each row key is in one chunk and writes only its own slots and found flags. +// +// The client reports a deadline or cancellation as a gRPC status that does not wrap the context error, so +// the returned error also wraps context.Cause(ctx). +func (s *BigtableOnlineStore) readChunks(ctx context.Context, chunks []*bigtableChunk, result *bigtableReadResult, + stats *bigtableReadStats) error { + slots := min(len(chunks), s.cfg.MaxConcurrentChunks) + if s.inflight != nil { + slots = min(slots, s.cfg.MaxInflightReads) + } + if slots == 0 { + return nil + } + stats.rounds = (len(chunks) + slots - 1) / slots + admitted := time.Now() + releaseRead, err := s.admitRead(ctx, slots) + stats.inflightWait = time.Since(admitted) + if err != nil { + return err + } + defer releaseRead() + + group, groupCtx := errgroup.WithContext(ctx) + callSlots := make(chan struct{}, slots) + var dispatchErr error + for _, chunk := range chunks { + release, err := acquireCallSlot(groupCtx, callSlots, chunk.tableName, stats) + if err != nil { + dispatchErr = err + break + } + group.Go(func() error { + defer release() + return chunk.read(groupCtx, result) + }) + } + // A chunk's own error, which cancelled groupCtx, comes before the dispatch error it caused. + err = group.Wait() + if err == nil { + err = dispatchErr + } + for _, chunk := range chunks { + stats.rowsFound += chunk.rowsFound + } + return withContextCause(ctx, err) +} + +// withContextCause appends context.Cause(ctx) to err when ctx has ended, even if err came from something +// else first (a corrupt cell, say); err still leads the message. It returns err unchanged otherwise. +func withContextCause(ctx context.Context, err error) error { + if err != nil && ctx.Err() != nil && !errors.Is(err, context.Cause(ctx)) { + return fmt.Errorf("%w (%w)", err, context.Cause(ctx)) + } + return err +} + +// admitRead reserves n max_inflight_reads slots for one read. When they are not free it waits up to +// max_inflight_wait_ms (0 does not wait) and then rejects the read with a *bigtableReadRejectedError, so +// an overloaded server turns work away before it reaches Bigtable instead of queueing it until +// read_timeout_ms. A read whose own deadline or cancellation ends the wait gets that error instead. With +// max_inflight_reads unset it returns at once. release returns the slots. +func (s *BigtableOnlineStore) admitRead(ctx context.Context, n int) (release func(), err error) { + if s.inflight == nil { + return func() {}, nil + } + release = func() { s.inflight.Release(int64(n)) } + if s.inflight.TryAcquire(int64(n)) { + return release, nil + } + if s.cfg.MaxInflightWait > 0 { + waitCtx, cancel := context.WithTimeout(ctx, s.cfg.MaxInflightWait) + err := s.inflight.Acquire(waitCtx, int64(n)) + cancel() + if err == nil { + return release, nil + } + if ctx.Err() != nil { + return nil, fmt.Errorf("bigtable online store: waiting for %d of max_inflight_reads %d: %w", + n, s.cfg.MaxInflightReads, context.Cause(ctx)) + } + } + return nil, &bigtableReadRejectedError{msg: fmt.Sprintf("bigtable online store: read rejected: %d of "+ + "max_inflight_reads %d not free within max_inflight_wait_ms %d", n, s.cfg.MaxInflightReads, + s.cfg.MaxInflightWait.Milliseconds())} +} + +// acquireCallSlot waits for one of the call's slots and adds the wait to stats (only readChunks' dispatch +// loop calls it, so no lock). release returns the slot. +func acquireCallSlot(ctx context.Context, callSlots chan struct{}, table string, + stats *bigtableReadStats) (release func(), err error) { + start := time.Now() + select { + case callSlots <- struct{}{}: + stats.callSlotWait += time.Since(start) + return func() { <-callSlots }, nil + case <-ctx.Done(): + stats.callSlotWait += time.Since(start) + return nil, fmt.Errorf("bigtable online store: read table %s: %w", table, context.Cause(ctx)) + } +} + +// read reads the chunk in one ReadRows and fills result. A decode error stops the stream from the callback, +// which cannot return it, so it is kept in fillErr. +func (c *bigtableChunk) read(ctx context.Context, result *bigtableReadResult) error { + if ctx.Err() != nil { + return fmt.Errorf("bigtable online store: read table %s: %w", c.tableName, context.Cause(ctx)) + } + c.dispatched = true + var fillErr error + err := c.table.ReadRows(ctx, c.keys, func(row bigtable.Row) bool { + if fillErr = result.fillRow(c.tableName, c.targets, row); fillErr != nil { + return false + } + c.rowsFound++ + return true + }, c.filter) + if err != nil { + return fmt.Errorf("bigtable online store: read table %s: %w", c.tableName, err) + } + return fillErr +} + +// fillRow decodes a row into its first entity's slots, copies them to any repeats of that entity, and +// marks the view found. +func (r *bigtableReadResult) fillRow(table string, targets map[string]*bigtableRowTarget, row bigtable.Row) error { + target, ok := targets[row.Key()] + if !ok { + return fmt.Errorf("bigtable online store: table %s returned unrequested row %q", table, row.Key()) + } + first := r.rows[target.entities[0]] + if err := decodeBigtableRow(row[bigtableFeatureFamily], target.view, first); err != nil { + return fmt.Errorf("bigtable online store: table %s, view %s: %w", table, target.view.name, err) + } + for i, entity := range target.entities { + if i > 0 { + copyViewSlots(r.rows[entity], first, target.view) + } + r.found[entity*r.numViews+target.view.order] = true + } + return nil +} + +// decodeBigtableRow writes the view's slots of one output row: each requested feature decoded straight +// into its slot, NullVal for one the row lacks, and the row's event_ts on all. A failed decode leaves the +// slots partly written, and the whole read fails. +func decodeBigtableRow(items []bigtable.ReadItem, view *bigtableViewRead, out []FeatureData) error { + writeNullViewSlots(out, view) + var eventTS *timestamppb.Timestamp + for _, item := range items { + qualifier := strings.TrimPrefix(item.Column, bigtableFeatureFamily+":") + if qualifier == bigtableEventTSQualifier { + ts, err := parseEventTS(item.Value) + if err != nil { + return fmt.Errorf("qualifier %s: %w", qualifier, err) + } + eventTS = ts + continue + } + positions, requested := view.positions[qualifier] + if !requested { + continue + } + value := &out[positions[0]].Value + if err := proto.Unmarshal(item.Value, value); err != nil { + return fmt.Errorf("qualifier %s: decode feast.types.Value: %w", qualifier, err) + } + for _, p := range positions[1:] { + out[p].Value.Val = value.Val + } + } + if eventTS == nil { + return fmt.Errorf("qualifier %s: missing from the row", bigtableEventTSQualifier) + } + for _, slot := range view.slots { + out[slot.index].Timestamp = timestamppb.Timestamp{Seconds: eventTS.GetSeconds(), Nanos: eventTS.GetNanos()} + } + return nil +} + +// writeNullViewSlots sets every slot of view in row to NullVal with a zero timestamp. +func writeNullViewSlots(row []FeatureData, view *bigtableViewRead) { + for _, slot := range view.slots { + row[slot.index] = FeatureData{ + Reference: serving.FeatureReferenceV2{FeatureViewName: view.name, FeatureName: slot.name}, + Value: types.Value{Val: &types.Value_NullVal{NullVal: types.Null_NULL}}, + } + } +} + +// copyViewSlots copies the view's slots of src into dst, sharing each decoded value. +func copyViewSlots(dst, src []FeatureData, view *bigtableViewRead) { + for _, slot := range view.slots { + from := &src[slot.index] + dst[slot.index] = FeatureData{ + Reference: serving.FeatureReferenceV2{FeatureViewName: view.name, FeatureName: slot.name}, + Timestamp: timestamppb.Timestamp{Seconds: from.Timestamp.GetSeconds(), Nanos: from.Timestamp.GetNanos()}, + Value: types.Value{Val: from.Value.Val}, + } + } +} + +// applyMissingData nils the row of an entity found in no view and fills NullVal for its missing views. +func (r *bigtableReadResult) applyMissingData(views []*bigtableViewRead) [][]FeatureData { + for entity, row := range r.rows { + found := r.found[entity*r.numViews : (entity+1)*r.numViews] + if !slices.Contains(found, true) { + r.rows[entity] = nil + continue + } + for _, view := range views { + if !found[view.order] { + writeNullViewSlots(row, view) + } + } + } + return r.rows +} + +// Destruct closes the client. It is safe to call more than once. +func (s *BigtableOnlineStore) Destruct() { + s.closeOnce.Do(func() { + if err := s.client.Close(); err != nil { + log.Warn().Err(err).Msg("bigtable online store: closing the client") + } + }) +} + +// table returns the cached handle for a table, opening it on first use. Safe for concurrent use. +func (s *BigtableOnlineStore) table(name string) *bigtable.Table { + if t, ok := s.tables.Load(name); ok { + return t.(*bigtable.Table) + } + t, _ := s.tables.LoadOrStore(name, s.client.Open(name)) + return t.(*bigtable.Table) +} + +// bigtableTableName ports Python's BigtableOnlineStore._get_table_name, including its md5 shortening of +// long names. Lengths count runes, as Python's len and slicing do. +func bigtableTableName(project string, entityNames []string) string { + entitiesPart := model.DUMMY_ENTITY_NAME + if len(entityNames) > 0 { + sorted := append([]string(nil), entityNames...) + sort.Strings(sorted) + entitiesPart = strings.Join(sorted, "-") + } + if runeLen(entitiesPart) > bigtableEntitiesPartMaxLength { + entitiesPart = md5Hex(entitiesPart)[:bigtableEntitiesPartMaxLength] + } + remaining := bigtableTableNameMaxLength - runeLen(entitiesPart) - 1 + projectPart := project + if runeLen(project) > remaining { + projectHash := md5Hex(project) + // Python's hexdigest()[:n] clamps at the 32 hex chars; a short entity part asks for more. + hashLength := min(remaining-bigtableProjectReadableLength-1, len(projectHash)) + projectPart = string([]rune(project)[:bigtableProjectReadableLength]) + "_" + projectHash[:hashLength] + } + return projectPart + "." + entitiesPart +} + +func runeLen(s string) int { + return len([]rune(s)) +} + +func md5Hex(s string) string { + sum := md5.Sum([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +// bigtableRowKeyFromHash is Python's BigtableOnlineStore._compute_row_key from an entity hash: the hash, +// "#", then the feature view name. +func bigtableRowKeyFromHash(hash, featureViewName string) string { + return hash + "#" + featureViewName +} + +// bigtableEntityHash is the row key before "#": the hex MurmurHash3 x64 128-bit hash (seed 0) of the +// serialized entity key. It is the same for every view, so reads compute it once per entity. +func bigtableEntityHash(entityKey *types.EntityKey, serializationVersion int64) (string, error) { + serKey, err := serializeEntityKey(entityKey, serializationVersion) + if err != nil { + return "", err + } + hash := bigtableMurmurHash(*serKey) + return hex.EncodeToString(hash[:]), nil +} + +// bigtableMurmurHash is MurmurHash3 x64 128-bit with seed 0 in the byte order of Python's +// mmh3.hash_bytes (h1 then h2, little-endian), using the pure Go github.com/spaolacci/murmur3. +func bigtableMurmurHash(data []byte) [16]byte { + h1, h2 := murmur3.Sum128WithSeed(data, 0) + var out [16]byte + binary.LittleEndian.PutUint64(out[:8], h1) + binary.LittleEndian.PutUint64(out[8:], h2) + return out +} + +// normalizeSerializationVersion maps an omitted entity_key_serialization_version (0) to 3, Python's +// default, and rejects every version other than 3. +func normalizeSerializationVersion(v int64) (int64, error) { + if v == 0 { + return bigtableSerializationVersion, nil + } + if v != bigtableSerializationVersion { + return 0, fmt.Errorf("bigtable online store: entity_key_serialization_version must be %d, got %d", + bigtableSerializationVersion, v) + } + return v, nil +} + +// parseEventTS parses Python's datetime.isoformat() event_ts; one without an offset is UTC. An offset with +// fractional seconds (+05:53:28.123456, from a tzinfo built on a timedelta with microseconds) is not +// supported: no IANA zone has one, and Go's time layouts cannot express it. +func parseEventTS(b []byte) (*timestamppb.Timestamp, error) { + s := string(b) + t, err := time.Parse(time.RFC3339Nano, s) + if err == nil { + return timestamppb.New(t), nil + } + for _, layout := range []string{secondsOffsetISOLayout, naiveISOLayout} { + if t, altErr := time.Parse(layout, s); altErr == nil { + return timestamppb.New(t), nil + } + } + return nil, fmt.Errorf("invalid event_ts %q: %w", s, err) +} diff --git a/go/internal/feast/onlinestore/bigtableonlinestore_helpers_test.go b/go/internal/feast/onlinestore/bigtableonlinestore_helpers_test.go new file mode 100644 index 00000000000..cbf806c7e01 --- /dev/null +++ b/go/internal/feast/onlinestore/bigtableonlinestore_helpers_test.go @@ -0,0 +1,80 @@ +package onlinestore + +import ( + "context" + "testing" + "time" + + "cloud.google.com/go/bigtable" + "cloud.google.com/go/bigtable/bttest" + "github.com/stretchr/testify/require" + "google.golang.org/api/option" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/feast-dev/feast/go/internal/feast/registry" + "github.com/feast-dev/feast/go/protos/feast/types" +) + +// testBigtableFeastProject is the Feast project of stores built by newTestBigtable; table names derive from it. +const testBigtableFeastProject = "feast_test" + +// newTestBigtable starts an in-memory Bigtable (bttest) and returns a store built on it from the +// online_store config map cfg, plus an admin client and a data client for creating tables and writing +// rows. srvOpts reach the bttest gRPC server, so tests can add interceptors (for example to count or +// delay ReadRows streams). Everything is closed when the test ends. +// +// It sets BIGTABLE_EMULATOR_HOST, which turns off the client's built-in Cloud Monitoring metrics, so +// tests using it cannot call t.Parallel. Dialing with option.WithGRPCConn also bypasses the client's own +// channel pool, so these tests do not exercise it: not its PingAndWarm priming at construction, which is +// what fails startup on bad credentials in production, nor the session data plane the client can use for +// single-key reads. +func newTestBigtable(t *testing.T, cfg map[string]interface{}, srvOpts ...grpc.ServerOption) (*BigtableOnlineStore, *bigtable.AdminClient, *bigtable.Client) { + t.Helper() + srv, err := bttest.NewServer("localhost:0", srvOpts...) + require.NoError(t, err) + t.Cleanup(srv.Close) + t.Setenv("BIGTABLE_EMULATOR_HOST", srv.Addr) + + conn, err := grpc.NewClient(srv.Addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + + parsed, err := parseBigtableConfig(cfg) + require.NoError(t, err) + require.NotEmpty(t, parsed.ProjectID, "newTestBigtable needs project_id in cfg; tests never resolve ADC") + + ctx := context.Background() + admin, err := bigtable.NewAdminClient(ctx, parsed.ProjectID, parsed.Instance, option.WithGRPCConn(conn)) + require.NoError(t, err) + t.Cleanup(func() { _ = admin.Close() }) + + data, err := bigtable.NewClient(ctx, parsed.ProjectID, parsed.Instance, option.WithGRPCConn(conn)) + require.NoError(t, err) + t.Cleanup(func() { _ = data.Close() }) + + repoConfig := ®istry.RepoConfig{Project: testBigtableFeastProject, OnlineStore: cfg} + store, err := newBigtableOnlineStore(ctx, testBigtableFeastProject, repoConfig, parsed, 5*time.Second, + option.WithGRPCConn(conn)) + require.NoError(t, err) + t.Cleanup(store.Destruct) + return store, admin, data +} + +// mustParseBigtableConfig parses an online_store config map as feature_store.yaml would give it. +func mustParseBigtableConfig(t *testing.T, m map[string]interface{}) bigtableConfig { + t.Helper() + cfg, err := parseBigtableConfig(m) + require.NoError(t, err) + return cfg +} + +// bigtableRowKey is Python's BigtableOnlineStore._compute_row_key for one entity key and view, built the +// way reads build it, so the parity tests pin the keys reads send. +func bigtableRowKey(entityKey *types.EntityKey, featureViewName string, serializationVersion int64) (string, error) { + hash, err := bigtableEntityHash(entityKey, serializationVersion) + if err != nil { + return "", err + } + return bigtableRowKeyFromHash(hash, featureViewName), nil +} diff --git a/go/internal/feast/onlinestore/bigtableonlinestore_read_test.go b/go/internal/feast/onlinestore/bigtableonlinestore_read_test.go new file mode 100644 index 00000000000..062885be0e2 --- /dev/null +++ b/go/internal/feast/onlinestore/bigtableonlinestore_read_test.go @@ -0,0 +1,1484 @@ +package onlinestore + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "math" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "cloud.google.com/go/bigtable" + btpb "cloud.google.com/go/bigtable/apiv2/bigtablepb" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + otelcodes "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "golang.org/x/sync/semaphore" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + + "github.com/feast-dev/feast/go/internal/feast/model" + "github.com/feast-dev/feast/go/protos/feast/types" +) + +// seedRow is one Bigtable row to write in family "features": qualifier -> raw cell bytes, all cells at +// timestamp Micros (a whole number of milliseconds, as Bigtable requires). +type seedRow struct { + Key string + Cells map[string][]byte + Micros int64 +} + +// seedRows creates table (with family "features") if it does not exist yet, then writes each row with +// its own Apply and an explicit cell timestamp. With no rows it only creates the table. +func seedRows(t *testing.T, admin *bigtable.AdminClient, client *bigtable.Client, table string, rows ...seedRow) { + t.Helper() + ctx := context.Background() + if err := admin.CreateTable(ctx, table); status.Code(err) != codes.AlreadyExists { + require.NoError(t, err) + } + if err := admin.CreateColumnFamily(ctx, table, bigtableFeatureFamily); status.Code(err) != codes.AlreadyExists { + require.NoError(t, err) + } + tbl := client.Open(table) + for _, r := range rows { + mut := bigtable.NewMutation() + for qualifier, value := range r.Cells { + mut.Set(bigtableFeatureFamily, qualifier, bigtable.Timestamp(r.Micros), value) + } + require.NoError(t, tbl.Apply(ctx, r.Key, mut)) + } +} + +// pyCell is a Python-written cell from testdata/bigtable_fixtures.json: the serialized value, the +// event_ts string Python wrote with it, and what both must decode to. +type pyCell struct { + raw []byte + eventTS []byte + want *types.Value + seconds int64 + nanos int32 +} + +// readEnv is a store on bttest plus the Python-produced cells to seed it with. +type readEnv struct { + store *BigtableOnlineStore + admin *bigtable.AdminClient + client *bigtable.Client + cells map[string]pyCell // by fixture name: "int64", "string", "float list", ... +} + +func newReadEnv(t *testing.T) *readEnv { + t.Helper() + return newReadEnvWithConfig(t, nil) +} + +// newReadEnvWithConfig is newReadEnv with extra online_store keys (instance and project_id are set) and +// options for the bttest server, such as a readRowsSpy. +func newReadEnvWithConfig(t *testing.T, extra map[string]interface{}, srvOpts ...grpc.ServerOption) *readEnv { + t.Helper() + cfg := map[string]interface{}{"instance": "i", "project_id": "p"} + for k, v := range extra { + cfg[k] = v + } + store, admin, client := newTestBigtable(t, cfg, srvOpts...) + env := &readEnv{store: store, admin: admin, client: client, cells: map[string]pyCell{}} + for _, c := range loadBigtableFixtures(t).Cells { + raw, err := base64.StdEncoding.DecodeString(c.ValueB64) + require.NoError(t, err) + want := &types.Value{} + require.NoError(t, protojson.Unmarshal(c.WantValue, want)) + env.cells[c.Name] = pyCell{raw: raw, eventTS: []byte(c.EventTS), want: want, seconds: c.WantSeconds, nanos: c.WantNanos} + } + for _, name := range []string{"int64", "string", "float list", "double", "bool"} { + require.Contains(t, env.cells, name) + } + return env +} + +// cell returns a fixture cell by name. +func (e *readEnv) cell(name string) pyCell { return e.cells[name] } + +// rowKey is the Python row key of entity key ek in view. +func (e *readEnv) rowKey(t *testing.T, ek *types.EntityKey, view string) string { + t.Helper() + key, err := bigtableRowKey(ek, view, e.store.serializationVersion) + require.NoError(t, err) + return key +} + +// read calls OnlineReadWithEntities with every view on entity "subscriber" unless byView says otherwise. +func (e *readEnv) read(entityKeys []*types.EntityKey, views, features []string, byView map[string][]string) ([][]FeatureData, error) { + if byView == nil { + byView = map[string][]string{} + for _, v := range views { + byView[v] = []string{"subscriber"} + } + } + return e.store.OnlineReadWithEntities(context.Background(), entityKeys, views, features, byView) +} + +const subscriberTable = testBigtableFeastProject + ".subscriber" + +func userKey(id string) *types.EntityKey { + return &types.EntityKey{ + JoinKeys: []string{"user_profile_id"}, + EntityValues: []*types.Value{{Val: &types.Value_StringVal{StringVal: id}}}, + } +} + +// cells builds a row's cells: event_ts from tsCell, then qualifier/cell pairs. +func cells(tsCell pyCell, pairs ...interface{}) map[string][]byte { + m := map[string][]byte{bigtableEventTSQualifier: tsCell.eventTS} + for i := 0; i < len(pairs); i += 2 { + switch v := pairs[i+1].(type) { + case pyCell: + m[pairs[i].(string)] = v.raw + case []byte: + m[pairs[i].(string)] = v + } + } + return m +} + +// assertSlot checks one output slot: reference, value and timestamp. A nil want means NullVal. +func assertSlot(t *testing.T, got *FeatureData, view, feature string, want *types.Value, seconds int64, nanos int32) { + t.Helper() + assert.Equal(t, view, got.Reference.FeatureViewName, "view of %s", feature) + assert.Equal(t, feature, got.Reference.FeatureName) + if want == nil { + want = &types.Value{Val: &types.Value_NullVal{NullVal: types.Null_NULL}} + } + assert.True(t, proto.Equal(want, &got.Value), "%s/%s: got %v, want %v", view, feature, &got.Value, want) + assert.Equal(t, seconds, got.Timestamp.GetSeconds(), "%s/%s seconds", view, feature) + assert.Equal(t, nanos, got.Timestamp.GetNanos(), "%s/%s nanos", view, feature) +} + +// assertCell checks a slot that holds fixture cell c and the row timestamp of tsCell. +func assertCell(t *testing.T, got *FeatureData, view, feature string, c, tsCell pyCell) { + t.Helper() + assertSlot(t, got, view, feature, c.want, tsCell.seconds, tsCell.nanos) +} + +func requireShape(t *testing.T, got [][]FeatureData, rowLens ...int) { + t.Helper() + require.Len(t, got, len(rowLens)) + for i, n := range rowLens { + if n < 0 { + require.Nil(t, got[i], "row %d", i) + continue + } + require.NotNil(t, got[i], "row %d", i) + require.Len(t, got[i], n, "row %d", i) + } +} + +func TestBigtableReadAllFeatures(t *testing.T) { + e := newReadEnv(t) + i64, str, fl := e.cell("int64"), e.cell("string"), e.cell("float list") + u1, u2 := userKey("u1"), userKey("u2") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f1", i64, "f2", str), Micros: 1000}, + seedRow{Key: e.rowKey(t, u2, "fvA"), Cells: cells(str, "f1", fl, "f2", i64), Micros: 1000}, + ) + got, err := e.read([]*types.EntityKey{u1, u2}, []string{"fvA", "fvA"}, []string{"f1", "f2"}, nil) + require.NoError(t, err) + requireShape(t, got, 2, 2) + assertCell(t, &got[0][0], "fvA", "f1", i64, i64) + assertCell(t, &got[0][1], "fvA", "f2", str, i64) + assertCell(t, &got[1][0], "fvA", "f1", fl, str) // +05:30 event_ts + assertCell(t, &got[1][1], "fvA", "f2", i64, str) +} + +func TestBigtableReadFeatureSubset(t *testing.T) { + e := newReadEnv(t) + i64, str := e.cell("int64"), e.cell("string") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f1", i64, "f2", str), Micros: 1000}) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA"}, []string{"f2"}, nil) + require.NoError(t, err) + requireShape(t, got, 1) + assertCell(t, &got[0][0], "fvA", "f2", str, i64) +} + +func TestBigtableReadTwoViewsOneTable(t *testing.T) { + e := newReadEnv(t) + i64, str, dbl := e.cell("int64"), e.cell("string"), e.cell("double") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "a1", i64), Micros: 1000}, + seedRow{Key: e.rowKey(t, u1, "fvB"), Cells: cells(str, "b1", dbl, "b2", str), Micros: 1000}, + ) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvB", "fvA", "fvB"}, []string{"b2", "a1", "b1"}, nil) + require.NoError(t, err) + requireShape(t, got, 3) + assertCell(t, &got[0][0], "fvB", "b2", str, str) + assertCell(t, &got[0][1], "fvA", "a1", i64, i64) + assertCell(t, &got[0][2], "fvB", "b1", dbl, str) +} + +// TestBigtableReadTwoTablesInOneCall: fvA is on entity a, fvB on entity b, both with join key +// user_profile_id. One call must read both tables. +func TestBigtableReadTwoTablesInOneCall(t *testing.T) { + e := newReadEnv(t) + i64, str, bl := e.cell("int64"), e.cell("string"), e.cell("bool") + u1, u2 := userKey("u1"), userKey("u2") + tableA, tableB := testBigtableFeastProject+".a", testBigtableFeastProject+".b" + seedRows(t, e.admin, e.client, tableA, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f", i64), Micros: 1000}) + seedRows(t, e.admin, e.client, tableB, + seedRow{Key: e.rowKey(t, u1, "fvB"), Cells: cells(str, "f", str), Micros: 1000}, + seedRow{Key: e.rowKey(t, u2, "fvB"), Cells: cells(i64, "f", bl), Micros: 1000}, + ) + byView := map[string][]string{"fvA": {"a"}, "fvB": {"b"}} + got, err := e.read([]*types.EntityKey{u1, u2}, []string{"fvA", "fvB"}, []string{"f", "f"}, byView) + require.NoError(t, err) + requireShape(t, got, 2, 2) + assertCell(t, &got[0][0], "fvA", "f", i64, i64) + assertCell(t, &got[0][1], "fvB", "f", str, str) + assertSlot(t, &got[1][0], "fvA", "f", nil, 0, 0) // u2 has no fvA row in table a + assertCell(t, &got[1][1], "fvB", "f", bl, i64) +} + +// TestBigtableReadEntityless reads an entityless view from ".__dummy". The serving layer +// passes the model's ["__dummy"]; an empty entity list names the same table. +func TestBigtableReadEntityless(t *testing.T) { + for name, entities := range map[string][]string{"model dummy entity": {model.DUMMY_ENTITY_NAME}, "no entities": {}} { + t.Run(name, func(t *testing.T) { + e := newReadEnv(t) + i64 := e.cell("int64") + dummy := &types.EntityKey{ + JoinKeys: []string{model.DUMMY_ENTITY_ID}, + EntityValues: []*types.Value{{Val: &types.Value_StringVal{StringVal: model.DUMMY_ENTITY_VAL}}}, + } + seedRows(t, e.admin, e.client, testBigtableFeastProject+".__dummy", + seedRow{Key: e.rowKey(t, dummy, "global_stats"), Cells: cells(i64, "total", i64), Micros: 1000}) + got, err := e.read([]*types.EntityKey{dummy}, []string{"global_stats"}, []string{"total"}, + map[string][]string{"global_stats": entities}) + require.NoError(t, err) + requireShape(t, got, 1) + assertCell(t, &got[0][0], "global_stats", "total", i64, i64) + }) + } +} + +func TestBigtableReadMissingRow(t *testing.T) { + e := newReadEnv(t) + i64 := e.cell("int64") + u1, ghost := userKey("u1"), userKey("ghost") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f1", i64), Micros: 1000}) + got, err := e.read([]*types.EntityKey{ghost, u1}, []string{"fvA"}, []string{"f1"}, nil) + require.NoError(t, err) + requireShape(t, got, -1, 1) + assertCell(t, &got[1][0], "fvA", "f1", i64, i64) +} + +func TestBigtableReadPartialEntity(t *testing.T) { + e := newReadEnv(t) + i64 := e.cell("int64") + u1, ghost := userKey("u1"), userKey("ghost") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "a1", i64), Micros: 1000}) + got, err := e.read([]*types.EntityKey{u1, ghost}, []string{"fvA", "fvB", "fvB"}, []string{"a1", "b1", "b2"}, nil) + require.NoError(t, err) + requireShape(t, got, 3, -1) + assertCell(t, &got[0][0], "fvA", "a1", i64, i64) + assertSlot(t, &got[0][1], "fvB", "b1", nil, 0, 0) + assertSlot(t, &got[0][2], "fvB", "b2", nil, 0, 0) +} + +func TestBigtableReadMissingFeature(t *testing.T) { + e := newReadEnv(t) + i64, str := e.cell("int64"), e.cell("string") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(str, "f1", i64), Micros: 1000}) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA", "fvA"}, []string{"f1", "f2"}, nil) + require.NoError(t, err) + requireShape(t, got, 2) + assertCell(t, &got[0][0], "fvA", "f1", i64, str) + assertSlot(t, &got[0][1], "fvA", "f2", nil, str.seconds, str.nanos) // NullVal keeps the row's event_ts +} + +func TestBigtableReadLatestVersionOnly(t *testing.T) { + e := newReadEnv(t) + i64, str := e.cell("int64"), e.cell("string") + u1 := userKey("u1") + key := e.rowKey(t, u1, "fvA") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: key, Cells: cells(i64, "f1", i64), Micros: 2000}, + seedRow{Key: key, Cells: cells(str, "f1", str), Micros: 1000}, // older version, written second + ) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA"}, []string{"f1"}, nil) + require.NoError(t, err) + requireShape(t, got, 1) + assertCell(t, &got[0][0], "fvA", "f1", i64, i64) +} + +func TestBigtableReadRegexMetacharacters(t *testing.T) { + e := newReadEnv(t) + i64, str, dbl := e.cell("int64"), e.cell("string"), e.cell("double") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "a.b", i64, "c+d", str, "aXb", dbl), Micros: 1000}) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA", "fvA"}, []string{"a.b", "c+d"}, nil) + require.NoError(t, err) + requireShape(t, got, 2) + assertCell(t, &got[0][0], "fvA", "a.b", i64, i64) + assertCell(t, &got[0][1], "fvA", "c+d", str, i64) +} + +func TestBigtableQualifierPattern(t *testing.T) { + plan, err := planBigtableRead("p", []string{"fvA", "fvB", "fvA", "fvA"}, []string{"c+d", "a.b", "a.b", "c+d"}, + map[string][]string{"fvA": {"e"}, "fvB": {"e"}}) + require.NoError(t, err) + require.Len(t, plan.tables, 1) + assert.Equal(t, `^(a\.b|c\+d|event_ts)$`, plan.tables[0].qualifierPattern()) +} + +// TestBigtableReadFilterKeepsNewestCellOnly pins the filter chain: the requested qualifiers, then +// LatestNFilter(1) (printed as col(*,1)). Dropping the latest-cell limit would return older versions, +// which Bigtable's in-memory tier never serves. +func TestBigtableReadFilterKeepsNewestCellOnly(t *testing.T) { + plan, err := planBigtableRead("p", []string{"fvA"}, []string{"f"}, map[string][]string{"fvA": {"e"}}) + require.NoError(t, err) + require.Len(t, plan.tables, 1) + assert.Equal(t, `(col(.*:^(f|event_ts)$) | col(*,1))`, plan.tables[0].readFilter().String()) +} + +// TestBigtableReadIgnoresUnrequestedQualifiers: a qualifier the request did not ask for must not change +// the slots or fail the read. +func TestBigtableReadIgnoresUnrequestedQualifiers(t *testing.T) { + // A stale qualifier left by an older schema; the server-side filter drops it. + t.Run("stale qualifier", func(t *testing.T) { + e := newReadEnv(t) + i64 := e.cell("int64") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f1", i64, "old_feature", []byte{0xff, 0xff}), Micros: 1000}) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA"}, []string{"f1"}, nil) + require.NoError(t, err) + requireShape(t, got, 1) + assertCell(t, &got[0][0], "fvA", "f1", i64, i64) + }) + // The filter is the union of the table's requested names, so fvA's corrupt b1 passes it because + // fvB:b1 is requested. The callback must skip it for fvA and still read fvB's own b1. + t.Run("other view's qualifier", func(t *testing.T) { + e := newReadEnv(t) + i64, str := e.cell("int64"), e.cell("string") + u1 := userKey("u1") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "a1", i64, "b1", []byte{0xff, 0xff}), Micros: 1000}, + seedRow{Key: e.rowKey(t, u1, "fvB"), Cells: cells(str, "b1", str), Micros: 1000}, + ) + got, err := e.read([]*types.EntityKey{u1}, []string{"fvA", "fvB"}, []string{"a1", "b1"}, nil) + require.NoError(t, err) + requireShape(t, got, 2) + assertCell(t, &got[0][0], "fvA", "a1", i64, i64) + assertCell(t, &got[0][1], "fvB", "b1", str, str) + }) +} + +// TestBigtableReadDuplicatesAndSameNames: entity u1 at positions 0 and 2, fvA:f1 requested twice, and +// f1 in both fvA and fvB. Every position must get its own view's value. +func TestBigtableReadDuplicatesAndSameNames(t *testing.T) { + e := newReadEnv(t) + i64, str, fl, dbl := e.cell("int64"), e.cell("string"), e.cell("float list"), e.cell("double") + u1, u2 := userKey("u1"), userKey("u2") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, u1, "fvA"), Cells: cells(i64, "f1", i64, "f2", str), Micros: 1000}, + seedRow{Key: e.rowKey(t, u1, "fvB"), Cells: cells(str, "f1", fl), Micros: 1000}, + seedRow{Key: e.rowKey(t, u2, "fvA"), Cells: cells(str, "f1", dbl, "f2", i64), Micros: 1000}, + ) + got, err := e.read([]*types.EntityKey{u1, u2, u1}, + []string{"fvA", "fvA", "fvB", "fvA"}, []string{"f1", "f2", "f1", "f1"}, nil) + require.NoError(t, err) + requireShape(t, got, 4, 4, 4) + for _, row := range []int{0, 2} { + assertCell(t, &got[row][0], "fvA", "f1", i64, i64) + assertCell(t, &got[row][1], "fvA", "f2", str, i64) + assertCell(t, &got[row][2], "fvB", "f1", fl, str) + assertCell(t, &got[row][3], "fvA", "f1", i64, i64) + } + assertCell(t, &got[1][0], "fvA", "f1", dbl, str) + assertCell(t, &got[1][1], "fvA", "f2", i64, str) + assertSlot(t, &got[1][2], "fvB", "f1", nil, 0, 0) + assertCell(t, &got[1][3], "fvA", "f1", dbl, str) +} + +// TestBigtableReadCorruptCellsFail: corrupt data fails the whole read, never NOT_FOUND, and no partial +// result comes back even though the other entity's row is fine. +func TestBigtableReadCorruptCellsFail(t *testing.T) { + tests := []struct { + name string + cells func(e *readEnv) map[string][]byte + qualifier string + }{ + {"bad event_ts", func(e *readEnv) map[string][]byte { + return map[string][]byte{"event_ts": []byte("not a time"), "f1": e.cell("int64").raw} + }, "event_ts"}, + {"missing event_ts", func(e *readEnv) map[string][]byte { + return map[string][]byte{"f1": e.cell("int64").raw} + }, "event_ts"}, + {"undecodable value", func(e *readEnv) map[string][]byte { + return cells(e.cell("int64"), "f1", []byte{0xff, 0xff}) + }, "f1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := newReadEnv(t) + good, bad := userKey("good"), userKey("bad") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: e.rowKey(t, good, "fvA"), Cells: cells(e.cell("int64"), "f1", e.cell("int64")), Micros: 1000}, + seedRow{Key: e.rowKey(t, bad, "fvA"), Cells: tt.cells(e), Micros: 1000}, + ) + got, err := e.read([]*types.EntityKey{good, bad}, []string{"fvA"}, []string{"f1"}, nil) + require.Error(t, err) + assert.Nil(t, got) + assert.ErrorContains(t, err, subscriberTable) + assert.ErrorContains(t, err, "fvA") + assert.ErrorContains(t, err, tt.qualifier) + assert.Equal(t, 1, strings.Count(err.Error(), "bigtable online store:"), "one store prefix: %v", err) + }) + } +} + +// TestBigtableReadMissingTableErrors: a view whose table was never created fails with the table's +// name. +func TestBigtableReadMissingTableErrors(t *testing.T) { + e := newReadEnv(t) + got, err := e.read([]*types.EntityKey{userKey("u1")}, []string{"fvA"}, []string{"f1"}, + map[string][]string{"fvA": {"never_created"}}) + require.ErrorContains(t, err, testBigtableFeastProject+".never_created") + assert.Equal(t, codes.NotFound, status.Code(err), "the gRPC NotFound status stays wrapped") + assert.Nil(t, got) +} + +func TestBigtableReadInputValidation(t *testing.T) { + e := newReadEnv(t) + ctx := context.Background() + u1 := []*types.EntityKey{userKey("u1")} + + got, err := e.store.OnlineReadWithEntities(ctx, nil, nil, nil, nil) + require.NoError(t, err) + assert.Empty(t, got) + + // Entity keys but no features: one nil row per key, no error. + got, err = e.store.OnlineReadWithEntities(ctx, []*types.EntityKey{userKey("u1"), userKey("u2")}, nil, nil, nil) + require.NoError(t, err) + requireShape(t, got, -1, -1) + + _, err = e.store.OnlineReadWithEntities(ctx, u1, []string{"fvA", "fvA"}, []string{"f1"}, + map[string][]string{"fvA": {"subscriber"}}) + require.ErrorContains(t, err, "featureViewNames") + + got, err = e.store.OnlineReadWithEntities(ctx, u1, []string{"fvA", "fvB"}, []string{"f1", "f1"}, + map[string][]string{"fvA": {"subscriber"}}) + require.ErrorContains(t, err, "fvB") + assert.Nil(t, got) +} + +func TestBigtableOnlineReadNeedsEntities(t *testing.T) { + e := newReadEnv(t) + got, err := e.store.OnlineRead(context.Background(), []*types.EntityKey{userKey("u1")}, []string{"fvA"}, []string{"f1"}) + require.ErrorIs(t, err, errors.ErrUnsupported) + assert.ErrorContains(t, err, "OnlineReadWithEntities") + assert.Nil(t, got) +} + +// readRowsSpy is a bttest stream interceptor that records every ReadRows request, tracks how many +// ReadRows streams are open at once, and can hold a stream (hold) after its request arrives and before +// the server answers it. Set hold before the server starts. +type readRowsSpy struct { + hold func(ctx context.Context, req *btpb.ReadRowsRequest) + + mu sync.Mutex + requests []*btpb.ReadRowsRequest + inFlight, maxInFlight int +} + +const readRowsMethod = "/google.bigtable.v2.Bigtable/ReadRows" + +func (s *readRowsSpy) option() grpc.ServerOption { + return grpc.StreamInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if info.FullMethod != readRowsMethod { + return handler(srv, ss) + } + s.mu.Lock() + s.inFlight++ + s.maxInFlight = max(s.maxInFlight, s.inFlight) + s.mu.Unlock() + defer func() { + s.mu.Lock() + s.inFlight-- + s.mu.Unlock() + }() + return handler(srv, &spyStream{ServerStream: ss, spy: s}) + }) +} + +func (s *readRowsSpy) reset() { + s.mu.Lock() + defer s.mu.Unlock() + s.requests, s.maxInFlight = nil, 0 +} + +func (s *readRowsSpy) requestCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.requests) +} + +// keysPerStreamByTable returns, for each table, the row-key count of each ReadRows stream it received. +func (s *readRowsSpy) keysPerStreamByTable() map[string][]int { + s.mu.Lock() + defer s.mu.Unlock() + out := map[string][]int{} + for _, req := range s.requests { + table := req.GetTableName()[strings.LastIndex(req.GetTableName(), "/")+1:] + out[table] = append(out[table], len(req.GetRows().GetRowKeys())) + } + return out +} + +type spyStream struct { + grpc.ServerStream + spy *readRowsSpy +} + +func (w *spyStream) RecvMsg(m any) error { + if err := w.ServerStream.RecvMsg(m); err != nil { + return err + } + if req, ok := m.(*btpb.ReadRowsRequest); ok { + w.spy.mu.Lock() + w.spy.requests = append(w.spy.requests, req) + w.spy.mu.Unlock() + if w.spy.hold != nil { + w.spy.hold(w.Context(), req) + } + } + return nil +} + +func requestHasKey(req *btpb.ReadRowsRequest, key string) bool { + for _, k := range req.GetRows().GetRowKeys() { + if string(k) == key { + return true + } + } + return false +} + +// userKeys returns n entity keys u000, u001, ... +func userKeys(n int) []*types.EntityKey { + keys := make([]*types.EntityKey, n) + for i := range keys { + keys[i] = userKey(fmt.Sprintf("u%03d", i)) + } + return keys +} + +// int64Cell is a serialized feast.types.Value holding v. +func int64Cell(t *testing.T, v int64) []byte { + t.Helper() + b, err := proto.Marshal(&types.Value{Val: &types.Value_Int64Val{Int64Val: v}}) + require.NoError(t, err) + return b +} + +// seedView writes view's row for every key in keys into table, feature "f" = the key's index. +func (e *readEnv) seedView(t *testing.T, table, view string, keys []*types.EntityKey) { + t.Helper() + rows := make([]seedRow, len(keys)) + for i, k := range keys { + rows[i] = seedRow{Key: e.rowKey(t, k, view), Cells: cells(e.cell("int64"), "f", int64Cell(t, int64(i))), Micros: 1000} + } + seedRows(t, e.admin, e.client, table, rows...) +} + +// TestBigtableReadChunkBoundaries: each table's row keys go out in ceil(keys/keys_per_request) +// ReadRows streams of at most keys_per_request keys, and every entity is filled. +func TestBigtableReadChunkBoundaries(t *testing.T) { + tableA, tableB := testBigtableFeastProject+".a", testBigtableFeastProject+".b" + byView := map[string][]string{"fvA": {"a"}, "fvB": {"b"}} + for _, perRequest := range []int{100, 50} { + t.Run(fmt.Sprintf("keys_per_request %d", perRequest), func(t *testing.T) { + spy := &readRowsSpy{} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(perRequest)}, spy.option()) + keys := userKeys(101) + e.seedView(t, tableA, "fvA", keys) + e.seedView(t, tableB, "fvB", keys) + i64 := e.cell("int64") + for _, n := range []int{0, 1, 100, 101} { + t.Run(fmt.Sprintf("%d entities", n), func(t *testing.T) { + spy.reset() + got, err := e.read(keys[:n], []string{"fvA", "fvB"}, []string{"f", "f"}, byView) + require.NoError(t, err) + require.Len(t, got, n) + for i, row := range got { + require.Len(t, row, 2, "entity %d", i) + want := &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(i)}} + assertSlot(t, &row[0], "fvA", "f", want, i64.seconds, i64.nanos) + assertSlot(t, &row[1], "fvB", "f", want, i64.seconds, i64.nanos) + } + streams := spy.keysPerStreamByTable() + for _, table := range []string{tableA, tableB} { + assert.Len(t, streams[table], (n+perRequest-1)/perRequest, "ReadRows streams on %s", table) + total := 0 + for _, c := range streams[table] { + assert.LessOrEqual(t, c, perRequest) + total += c + } + assert.Equal(t, n, total, "row keys sent to %s", table) + } + }) + } + }) + } +} + +// TestBigtableReadConcurrencyLimit: max_concurrent_chunks caps the streams of one call across all its +// tables, not per table. +func TestBigtableReadConcurrencyLimit(t *testing.T) { + // The first two streams wait for each other, so both are open at once whatever the timing; later + // streams pass at once. The 5 s bound only stops a broken test hanging. + var arrived atomic.Int32 + release := make(chan struct{}) + var releaseOnce sync.Once + spy := &readRowsSpy{hold: func(ctx context.Context, _ *btpb.ReadRowsRequest) { + if arrived.Add(1) >= 2 { + releaseOnce.Do(func() { close(release) }) + } + select { + case <-release: + case <-ctx.Done(): + case <-time.After(5 * time.Second): + } + }} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(10), "max_concurrent_chunks": float64(2)}, + spy.option()) + keys := userKeys(50) + e.seedView(t, testBigtableFeastProject+".a", "fvA", keys) + e.seedView(t, testBigtableFeastProject+".b", "fvB", keys) + got, err := e.read(keys, []string{"fvA", "fvB"}, []string{"f", "f"}, map[string][]string{"fvA": {"a"}, "fvB": {"b"}}) + require.NoError(t, err) + require.Len(t, got, 50) + assert.Equal(t, 10, spy.requestCount(), "5 chunks per table") + assert.Equal(t, 2, spy.maxInFlight, "streams open at once") +} + +// TestBigtableChunkSize: off, the size is always keys_per_request. On, keys_per_request is the floor and +// the size grows just enough to send the call's row keys in one round of max_concurrent_chunks, up to 100. +func TestBigtableChunkSize(t *testing.T) { + tests := []struct { + name string + adaptive bool + perRequest, maxChunks, nKeys int + want int + }{ + {"off, small read", false, 5, 50, 10, 5}, + {"off, large read", false, 5, 50, 500, 5}, + {"on, no keys", true, 5, 50, 0, 5}, + {"on, one key", true, 5, 50, 1, 5}, + {"on, 50 keys fit one round", true, 5, 50, 50, 5}, + {"on, 250 keys fill one round exactly", true, 5, 50, 250, 5}, + {"on, 251 keys grow to 6", true, 5, 50, 251, 6}, + {"on, 500 keys", true, 5, 50, 500, 10}, + {"on, 501 keys round up", true, 5, 50, 501, 11}, + {"on, 1500 keys", true, 5, 50, 1500, 30}, + {"on, capped at 100", true, 5, 50, 100000, 100}, + {"on, keys_per_request 100 always 100", true, 100, 50, 50, 100}, + {"on, keys_per_request 100 on a large read", true, 100, 50, 100000, 100}, + {"on, one stream", true, 5, 1, 30, 30}, + {"on, one stream capped at 100", true, 5, 1, 1000, 100}, + {"on, max_concurrent_chunks at its limit", true, 5, math.MaxInt32, 1000, 5}, + {"on, keys at the int32 limit", true, 5, math.MaxInt32, math.MaxInt32, 5}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := bigtableConfig{AdaptiveChunking: tt.adaptive, KeysPerRequest: tt.perRequest, MaxConcurrentChunks: tt.maxChunks} + assert.Equal(t, tt.want, bigtableChunkSize(cfg, tt.nKeys)) + }) + } +} + +// TestBigtableReadAdaptiveChunking: with keys_per_request 5 and 8 streams, adaptive_chunking keeps +// 5-key chunks while a read fits one round (40 keys), and above that sends one round of larger chunks, +// up to 100 keys each. Every entity is filled. +func TestBigtableReadAdaptiveChunking(t *testing.T) { + table := testBigtableFeastProject + ".a" + byView := map[string][]string{"fvA": {"a"}} + tests := []struct { + name string + adaptive bool + entities int + wantStreams, wantMaxKeys, wantInFlight int + }{ + {"off, 20 entities", false, 20, 4, 5, 4}, + {"on, 20 entities keep 5-key chunks", true, 20, 4, 5, 4}, + {"on, 1 entity", true, 1, 1, 5, 1}, + {"off, 50 entities take two rounds", false, 50, 10, 5, 8}, + {"on, 50 entities take one round of 7", true, 50, 8, 7, 8}, + {"on, 1000 entities capped at 100 keys", true, 1000, 10, 100, 8}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Hold every stream until wantInFlight have arrived, so the in-flight count shows the chunks run in + // parallel without depending on timing. The 5 s bound only stops a hang when fewer arrive; the + // maxInFlight assertion then fails. + var arrived atomic.Int32 + release := make(chan struct{}) + var releaseOnce sync.Once + spy := &readRowsSpy{hold: func(ctx context.Context, _ *btpb.ReadRowsRequest) { + if int(arrived.Add(1)) >= tt.wantInFlight { + releaseOnce.Do(func() { close(release) }) + } + select { + case <-release: + case <-ctx.Done(): + case <-time.After(5 * time.Second): + } + }} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(5), + "max_concurrent_chunks": float64(8), "adaptive_chunking": tt.adaptive}, spy.option()) + keys := userKeys(tt.entities) + e.seedView(t, table, "fvA", keys) + spy.reset() + got, err := e.read(keys, []string{"fvA"}, []string{"f"}, byView) + require.NoError(t, err) + require.Len(t, got, tt.entities) + i64 := e.cell("int64") + for i, row := range got { + want := &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(i)}} + assertSlot(t, &row[0], "fvA", "f", want, i64.seconds, i64.nanos) + } + streams := spy.keysPerStreamByTable()[table] + assert.Len(t, streams, tt.wantStreams, "ReadRows streams") + total := 0 + for _, c := range streams { + assert.LessOrEqual(t, c, tt.wantMaxKeys) + total += c + } + assert.Equal(t, tt.entities, total, "row keys sent") + assert.Equal(t, tt.wantInFlight, spy.maxInFlight, "streams open at once") + }) + } +} + +// TestBigtableReadAdaptiveChunkingTwoTables: the chunk size comes from the call's total row keys and each +// table is cut separately, so a call over two tables can plan more ReadRows than max_concurrent_chunks; +// only the number in flight stays capped. +func TestBigtableReadAdaptiveChunkingTwoTables(t *testing.T) { + tableA, tableB := testBigtableFeastProject+".a", testBigtableFeastProject+".b" + byView := map[string][]string{"fvA": {"a"}, "fvB": {"b"}} + tests := []struct { + name string + maxChunks, entities int + wantPerTable, wantMaxKeys int + }{ + // 100 row keys over 8 streams: size 13, so each table's 50 keys are 4 chunks, 8 in all. + {"balanced", 8, 50, 4, 13}, + // 20 row keys over 8 streams fit one round at the floor of 5: each table's 10 keys are 2 chunks. + {"floor", 8, 10, 2, 5}, + // 60 row keys over 3 streams: size 20, so each table's 30 keys are 2 chunks, 4 in all. + {"more chunks than streams", 3, 30, 2, 20}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spy := &readRowsSpy{} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(5), + "max_concurrent_chunks": float64(tt.maxChunks), "adaptive_chunking": true}, spy.option()) + keys := userKeys(tt.entities) + e.seedView(t, tableA, "fvA", keys) + e.seedView(t, tableB, "fvB", keys) + spy.reset() + got, err := e.read(keys, []string{"fvA", "fvB"}, []string{"f", "f"}, byView) + require.NoError(t, err) + require.Len(t, got, tt.entities) + i64 := e.cell("int64") + for i, row := range got { + want := &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(i)}} + assertSlot(t, &row[0], "fvA", "f", want, i64.seconds, i64.nanos) + assertSlot(t, &row[1], "fvB", "f", want, i64.seconds, i64.nanos) + } + streams := spy.keysPerStreamByTable() + for _, table := range []string{tableA, tableB} { + assert.Len(t, streams[table], tt.wantPerTable, "ReadRows streams on %s", table) + total := 0 + for _, c := range streams[table] { + assert.LessOrEqual(t, c, tt.wantMaxKeys) + total += c + } + assert.Equal(t, tt.entities, total, "row keys sent to %s", table) + } + assert.LessOrEqual(t, spy.maxInFlight, tt.maxChunks, "streams open at once") + }) + } +} + +// TestBigtableClientConfig: the app profile is passed through and everything else keeps the library's +// defaults. +func TestBigtableClientConfig(t *testing.T) { + assert.Equal(t, bigtable.ClientConfig{AppProfile: "serve"}, bigtableClientConfig(bigtableConfig{AppProfile: "serve"})) + assert.Equal(t, bigtable.ClientConfig{}, bigtableClientConfig(bigtableConfig{})) +} + +// TestBigtableAdmitRead: with max_inflight_reads unset, a read is always admitted. With it set, a read +// that needs more slots than are free is rejected at once when max_inflight_wait_ms is 0; with a wait, it +// is admitted when slots free within the wait and rejected when they do not. A rejection is +// RESOURCE_EXHAUSTED; a read whose own context ends the wait gets the context error instead. +func TestBigtableAdmitRead(t *testing.T) { + ctx := context.Background() + release, err := (&BigtableOnlineStore{}).admitRead(ctx, 50) + require.NoError(t, err) + release() + + newStore := func(wait time.Duration) *BigtableOnlineStore { + return &BigtableOnlineStore{inflight: semaphore.NewWeighted(2), + cfg: bigtableConfig{MaxInflightReads: 2, MaxInflightWait: wait}} + } + assertRejected := func(t *testing.T, err error) { + t.Helper() + var rejected *bigtableReadRejectedError + require.ErrorAs(t, err, &rejected) + assert.Equal(t, codes.ResourceExhausted, status.Code(err)) + assert.ErrorContains(t, err, "2 of max_inflight_reads 2 not free") + } + + t.Run("fail fast", func(t *testing.T) { + s := newStore(0) + held, err := s.admitRead(ctx, 1) + require.NoError(t, err) + _, err = s.admitRead(ctx, 2) + assertRejected(t, err) + held() + release, err := s.admitRead(ctx, 2) + require.NoError(t, err, "released slots are free again") + release() + }) + t.Run("admitted within the wait", func(t *testing.T) { + s := newStore(5 * time.Second) + held, err := s.admitRead(ctx, 2) + require.NoError(t, err) + time.AfterFunc(20*time.Millisecond, held) + release, err := s.admitRead(ctx, 2) + require.NoError(t, err) + release() + }) + t.Run("rejected after the wait", func(t *testing.T) { + s := newStore(20 * time.Millisecond) + held, err := s.admitRead(ctx, 1) + require.NoError(t, err) + defer held() + start := time.Now() + _, err = s.admitRead(ctx, 2) + assertRejected(t, err) + assert.GreaterOrEqual(t, time.Since(start), 20*time.Millisecond) + }) + t.Run("caller's context ends the wait", func(t *testing.T) { + s := newStore(5 * time.Second) + held, err := s.admitRead(ctx, 2) + require.NoError(t, err) + defer held() + cancelled, cancel := context.WithCancel(ctx) + cancel() + _, err = s.admitRead(cancelled, 1) + require.ErrorIs(t, err, context.Canceled) + assert.ErrorContains(t, err, "max_inflight_reads 2") + assert.False(t, errors.As(err, new(*bigtableReadRejectedError)), "not a rejection") + }) +} + +// TestBigtableReadMaxInflightReads: max_inflight_reads caps the ReadRows in flight across concurrent +// calls, which max_concurrent_chunks (per call) does not. 4 callers of 4 chunks each, with 8 streams per +// call and a long max_inflight_wait_ms, never have more than 3 streams open at once, and every call is +// filled. +func TestBigtableReadMaxInflightReads(t *testing.T) { + const limit = 3 + // Hold the first streams until limit have arrived, so the in-flight count reaches the cap without + // depending on timing; later streams pass at once. The 5 s bound only stops a hang. + var arrived atomic.Int32 + release := make(chan struct{}) + var releaseOnce sync.Once + spy := &readRowsSpy{hold: func(ctx context.Context, _ *btpb.ReadRowsRequest) { + if int(arrived.Add(1)) >= limit { + releaseOnce.Do(func() { close(release) }) + } + select { + case <-release: + case <-ctx.Done(): + case <-time.After(5 * time.Second): + } + }} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(5), + "max_concurrent_chunks": float64(8), "max_inflight_reads": float64(limit), + "max_inflight_wait_ms": float64(5000)}, spy.option()) + keys := userKeys(20) + e.seedView(t, subscriberTable, "fvA", keys) + spy.reset() + var wg sync.WaitGroup + errs := make([]error, 4) + results := make([][][]FeatureData, 4) + for c := range errs { + wg.Add(1) + go func() { + defer wg.Done() + results[c], errs[c] = e.store.OnlineReadWithEntities(context.Background(), keys, []string{"fvA"}, + []string{"f"}, map[string][]string{"fvA": {"subscriber"}}) + }() + } + wg.Wait() + i64 := e.cell("int64") + for c := range errs { + require.NoError(t, errs[c], "caller %d", c) + require.Len(t, results[c], 20) + for i, row := range results[c] { + want := &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(i)}} + assertSlot(t, &row[0], "fvA", "f", want, i64.seconds, i64.nanos) + } + } + assert.Equal(t, 16, spy.requestCount(), "4 chunks per caller") + assert.Equal(t, limit, spy.maxInFlight, "streams open at once across callers") +} + +// TestBigtableReadMaxInflightReadsRejects: with max_inflight_reads 2 and no max_inflight_wait_ms, a read +// of 2 chunks while another read holds 1 slot is rejected at once as RESOURCE_EXHAUSTED, sends no ReadRows +// (whole reads are admitted, not single chunks) and is counted under status "rejected". A read whose +// deadline ends its wait for slots fails with context.DeadlineExceeded and also sends nothing. +func TestBigtableReadMaxInflightReadsRejects(t *testing.T) { + for _, tt := range []struct { + name string + waitMs float64 + }{ + {"fail fast", 0}, + {"deadline ends the wait", 10000}, + } { + t.Run(tt.name, func(t *testing.T) { + arrived := make(chan struct{}) + unblock := make(chan struct{}) + var once sync.Once + spy := &readRowsSpy{hold: func(ctx context.Context, _ *btpb.ReadRowsRequest) { + once.Do(func() { close(arrived) }) + select { + case <-unblock: + case <-ctx.Done(): + case <-time.After(5 * time.Second): + } + }} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(5), + "max_inflight_reads": float64(2), "max_inflight_wait_ms": tt.waitMs}, spy.option()) + keys := userKeys(10) + e.seedView(t, subscriberTable, "fvA", keys) + read := func(ctx context.Context, keys []*types.EntityKey) ([][]FeatureData, error) { + return e.store.OnlineReadWithEntities(ctx, keys, []string{"fvA"}, []string{"f"}, + map[string][]string{"fvA": {"subscriber"}}) + } + spy.reset() + holderDone := make(chan error, 1) + go func() { + _, err := read(context.Background(), keys[:3]) + holderDone <- err + }() + <-arrived // the first read holds 1 of the 2 slots + rejectedBefore := durationSamples(t, "rejected") + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + got, err := read(ctx, keys) // 2 chunks + assert.Nil(t, got) + if tt.waitMs == 0 { + assert.Equal(t, codes.ResourceExhausted, status.Code(err)) + assert.ErrorContains(t, err, "2 of max_inflight_reads 2 not free within max_inflight_wait_ms 0") + assert.Equal(t, rejectedBefore+1, durationSamples(t, "rejected")) + } else { + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.ErrorContains(t, err, "max_inflight_reads 2") + assert.Equal(t, rejectedBefore, durationSamples(t, "rejected")) + } + assert.Equal(t, 1, spy.requestCount(), "the second read sent no ReadRows") + close(unblock) + require.NoError(t, <-holderDone) + }) + } +} + +// TestBigtableClientConfigMetrics: disable_metrics sets the no-op metrics provider; left unset, the provider +// stays nil, which the library reads as its default Cloud Monitoring exporter. +func TestBigtableClientConfigMetrics(t *testing.T) { + assert.Nil(t, bigtableClientConfig(bigtableConfig{}).MetricsProvider) + assert.Equal(t, bigtable.NoopMetricsProvider{}, bigtableClientConfig(bigtableConfig{DisableMetrics: true}).MetricsProvider) +} + +// TestBigtableMetricsMode: the startup log names why metrics are off, the config switch first. +func TestBigtableMetricsMode(t *testing.T) { + t.Setenv("BIGTABLE_EMULATOR_HOST", "") + assert.Equal(t, "default", bigtableMetricsMode(bigtableConfig{})) + assert.Equal(t, "disabled (disable_metrics)", bigtableMetricsMode(bigtableConfig{DisableMetrics: true})) + t.Setenv("BIGTABLE_EMULATOR_HOST", "localhost:1") + assert.Equal(t, "disabled (emulator)", bigtableMetricsMode(bigtableConfig{})) + assert.Equal(t, "disabled (disable_metrics)", bigtableMetricsMode(bigtableConfig{DisableMetrics: true})) +} + +// TestBigtableReadFirstChunkErrorCancelsOthers: one of 5 chunks hits a corrupt cell while the other 4 +// are held open by the server. The decode error must cancel them, so the call returns that error well +// before the caller's 2 s deadline. +func TestBigtableReadFirstChunkErrorCancelsOthers(t *testing.T) { + spy := &readRowsSpy{} + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(10), "max_concurrent_chunks": float64(5)}, + spy.option()) + keys := userKeys(50) + e.seedView(t, subscriberTable, "fvA", keys) + badKey := e.rowKey(t, keys[0], "fvA") + seedRows(t, e.admin, e.client, subscriberTable, + seedRow{Key: badKey, Cells: cells(e.cell("int64"), "f", []byte{0xff, 0xff}), Micros: 2000}) + spy.hold = func(ctx context.Context, req *btpb.ReadRowsRequest) { + deadline := time.After(3 * time.Second) + for { + // The bad chunk waits for all 5 streams to reach the server; the others wait to be cancelled. + if requestHasKey(req, badKey) && spy.requestCount() == 5 { + return + } + select { + case <-ctx.Done(): + return + case <-deadline: + return + case <-time.After(5 * time.Millisecond): + } + } + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + start := time.Now() + got, err := e.store.OnlineReadWithEntities(ctx, keys, []string{"fvA"}, []string{"f"}, + map[string][]string{"fvA": {"subscriber"}}) + elapsed := time.Since(start) + require.Error(t, err) + assert.Nil(t, got) + assert.ErrorContains(t, err, "decode feast.types.Value", "the corrupt cell's error, not a cancellation") + assert.NotErrorIs(t, err, context.DeadlineExceeded) + assert.Less(t, elapsed, 2*time.Second) + assert.Equal(t, 5, spy.requestCount()) +} + +// TestBigtableReadContextCancelled: a context cancelled before the call, or while the server holds the +// ReadRows stream, fails the read with an error wrapping context.Canceled. +func TestBigtableReadContextCancelled(t *testing.T) { + read := func(e *readEnv, ctx context.Context, keys []*types.EntityKey) ([][]FeatureData, error) { + return e.store.OnlineReadWithEntities(ctx, keys, []string{"fvA"}, []string{"f"}, + map[string][]string{"fvA": {"subscriber"}}) + } + t.Run("before the call", func(t *testing.T) { + e := newReadEnv(t) + keys := userKeys(3) + e.seedView(t, subscriberTable, "fvA", keys) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + got, err := read(e, ctx, keys) + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, got) + }) + t.Run("mid-stream", func(t *testing.T) { + arrived := make(chan struct{}) + var once sync.Once + spy := &readRowsSpy{hold: func(ctx context.Context, _ *btpb.ReadRowsRequest) { + once.Do(func() { close(arrived) }) + select { // released by the client's cancellation; the bound only stops a broken test hanging + case <-ctx.Done(): + case <-time.After(5 * time.Second): + } + }} + e := newReadEnvWithConfig(t, nil, spy.option()) + keys := userKeys(3) + e.seedView(t, subscriberTable, "fvA", keys) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + <-arrived + cancel() + }() + start := time.Now() + got, err := read(e, ctx, keys) + require.ErrorIs(t, err, context.Canceled) + assert.Nil(t, got) + assert.Less(t, time.Since(start), 5*time.Second, "the cancellation, not the hold bound, ended the read") + assert.Equal(t, 1, spy.requestCount()) + }) +} + +// TestBigtableReadTimeout: read_timeout_ms bounds the read, the caller's shorter deadline still wins, +// and a budget the read fits in changes nothing. The server holds every ReadRows stream for 50 ms. +func TestBigtableReadTimeout(t *testing.T) { + tests := []struct { + name string + readTimeoutMs float64 + callerDeadline time.Duration // 0: none + wantBudgetErr bool // the error names read_timeout_ms + wantErr bool + }{ + {name: "budget expires", readTimeoutMs: 1, wantErr: true, wantBudgetErr: true}, + {name: "caller deadline is shorter", readTimeoutMs: 60000, callerDeadline: time.Millisecond, wantErr: true}, + {name: "read fits the budget", readTimeoutMs: 5000}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spy := &readRowsSpy{hold: func(context.Context, *btpb.ReadRowsRequest) { time.Sleep(50 * time.Millisecond) }} + e := newReadEnvWithConfig(t, map[string]interface{}{"read_timeout_ms": tt.readTimeoutMs}, spy.option()) + keys := userKeys(3) + e.seedView(t, subscriberTable, "fvA", keys) + ctx := context.Background() + if tt.callerDeadline > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, tt.callerDeadline) + defer cancel() + } + got, err := e.store.OnlineReadWithEntities(ctx, keys, []string{"fvA"}, []string{"f"}, + map[string][]string{"fvA": {"subscriber"}}) + if !tt.wantErr { + require.NoError(t, err) + require.Len(t, got, 3) + return + } + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.Nil(t, got) + if tt.wantBudgetErr { + assert.ErrorContains(t, err, "read_timeout_ms") + } else { + assert.NotContains(t, err.Error(), "read_timeout_ms") + } + }) + } +} + +// TestBigtableReadDefaultTimeout: with read_timeout_ms unset and no caller deadline, a read still has a +// deadline, the 60 s default, so the client's retries of DeadlineExceeded, Unavailable and Aborted end +// (cloud.google.com/go/bigtable retries them until the context is done). +func TestBigtableReadDefaultTimeout(t *testing.T) { + read := func(e *readEnv, keys []*types.EntityKey) ([][]FeatureData, error) { + return e.store.OnlineReadWithEntities(context.Background(), keys, []string{"fvA"}, []string{"f"}, + map[string][]string{"fvA": {"subscriber"}}) + } + t.Run("the default budget reaches ReadRows", func(t *testing.T) { + var mu sync.Mutex + var timeLeft []time.Duration // per ReadRows stream; -1 when the stream has no deadline + srvOpt := grpc.StreamInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if info.FullMethod == readRowsMethod { + left := time.Duration(-1) + if deadline, ok := ss.Context().Deadline(); ok { + left = time.Until(deadline) + } + mu.Lock() + timeLeft = append(timeLeft, left) + mu.Unlock() + } + return handler(srv, ss) + }) + e := newReadEnvWithConfig(t, nil, srvOpt) + keys := userKeys(3) + e.seedView(t, subscriberTable, "fvA", keys) + got, err := read(e, keys) + require.NoError(t, err) + require.Len(t, got, 3) + mu.Lock() + defer mu.Unlock() + require.Len(t, timeLeft, 1) + assert.Greater(t, timeLeft[0], 50*time.Second, "ReadRows carries the 60 s default deadline") + assert.LessOrEqual(t, timeLeft[0], 60*time.Second) + }) + t.Run("retries of Unavailable end at the budget", func(t *testing.T) { + var attempts atomic.Int32 + srvOpt := grpc.StreamInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + if info.FullMethod != readRowsMethod { + return handler(srv, ss) + } + attempts.Add(1) + return status.Error(codes.Unavailable, "test: ReadRows is always unavailable") + }) + // A short budget stands in for the 60 s default, so the test proves the mechanism quickly. + e := newReadEnvWithConfig(t, map[string]interface{}{"read_timeout_ms": float64(300)}, srvOpt) + keys := userKeys(3) + e.seedView(t, subscriberTable, "fvA", keys) + start := time.Now() + got, err := read(e, keys) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.ErrorContains(t, err, "read_timeout_ms") + assert.Nil(t, got) + assert.Less(t, time.Since(start), 5*time.Second) + assert.GreaterOrEqual(t, attempts.Load(), int32(2), "the client retried Unavailable until the budget ended it") + }) +} + +// resultFingerprint renders a result as text: "nil" for a nil row, else each slot's reference, value +// bytes and timestamp. +func resultFingerprint(rows [][]FeatureData) string { + var b strings.Builder + for _, row := range rows { + if row == nil { + b.WriteString("nil\n") + continue + } + for i := range row { + v, err := proto.MarshalOptions{Deterministic: true}.Marshal(&row[i].Value) + if err != nil { + v = []byte(err.Error()) + } + fmt.Fprintf(&b, "%s/%s=%x@%d.%d;", row[i].Reference.FeatureViewName, row[i].Reference.FeatureName, + v, row[i].Timestamp.GetSeconds(), row[i].Timestamp.GetNanos()) + } + b.WriteString("\n") + } + return b.String() +} + +// assertConcurrentBaseline checks the single-threaded result of TestBigtableReadConcurrentCallers +// against what it seeded: fvA f1 = i for odd i, fvB b1 = 1000+i for i%3 == 0, a nil row when neither, +// and NullVal with a zero timestamp for the view an existing row lacks. +func assertConcurrentBaseline(t *testing.T, e *readEnv, got [][]FeatureData) { + t.Helper() + require.Len(t, got, 250) + i64, str := e.cell("int64"), e.cell("string") + for i, row := range got { + hasA, hasB := i%2 == 1, i%3 == 0 + if !hasA && !hasB { + require.Nil(t, row, "entity %d", i) + continue + } + require.Len(t, row, 3, "entity %d", i) + for _, slot := range []int{0, 2} { + if hasA { + assertSlot(t, &row[slot], "fvA", "f1", &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(i)}}, i64.seconds, i64.nanos) + } else { + assertSlot(t, &row[slot], "fvA", "f1", nil, 0, 0) + } + } + if hasB { + assertSlot(t, &row[1], "fvB", "b1", &types.Value{Val: &types.Value_Int64Val{Int64Val: int64(1000 + i)}}, str.seconds, str.nanos) + } else { + assertSlot(t, &row[1], "fvB", "b1", nil, 0, 0) + } + } +} + +// TestBigtableReadConcurrentCallers: 32 goroutines x 20 calls of 250 entities on one store, two views +// with partial coverage and one feature requested twice. Every result must equal the single-threaded +// one (run under -race). Rows are kept small because bttest compiles the column regex for every cell, +// which dominates the runtime. +func TestBigtableReadConcurrentCallers(t *testing.T) { + if testing.Short() { + t.Skip("32 x 20 reads of 250 entities against bttest") + } + e := newReadEnv(t) + keys := userKeys(250) + var rows []seedRow + for i, k := range keys { + if i%2 == 1 { // odd entities have an fvA row + rows = append(rows, seedRow{Key: e.rowKey(t, k, "fvA"), + Cells: cells(e.cell("int64"), "f1", int64Cell(t, int64(i))), Micros: 1000}) + } + if i%3 == 0 { // every 3rd entity has an fvB row; even non-multiples of 3 have neither + rows = append(rows, seedRow{Key: e.rowKey(t, k, "fvB"), + Cells: cells(e.cell("string"), "b1", int64Cell(t, int64(1000+i))), Micros: 1000}) + } + } + seedRows(t, e.admin, e.client, subscriberTable, rows...) + views, features := []string{"fvA", "fvB", "fvA"}, []string{"f1", "b1", "f1"} + want, err := e.read(keys, views, features, nil) + require.NoError(t, err) + assertConcurrentBaseline(t, e, want) + wantPrint := resultFingerprint(want) + + var wg sync.WaitGroup + for g := 0; g < 32; g++ { + wg.Add(1) + go func() { + defer wg.Done() + for c := 0; c < 20; c++ { + got, err := e.read(keys, views, features, nil) + if !assert.NoError(t, err) || !assert.Equal(t, wantPrint, resultFingerprint(got)) { + return + } + } + }() + } + wg.Wait() +} + +// onlineReadSpanRecorder keeps only bigtable.OnlineRead spans of traces a span test registered, so spans +// from every other test in the process (the client's own, other reads) never pile up in it. +type onlineReadSpanRecorder struct { + *tracetest.SpanRecorder + traces sync.Map // trace.TraceID -> struct{} +} + +func (r *onlineReadSpanRecorder) OnStart(context.Context, sdktrace.ReadWriteSpan) {} + +func (r *onlineReadSpanRecorder) OnEnd(s sdktrace.ReadOnlySpan) { + if _, ok := r.traces.Load(s.SpanContext().TraceID()); ok && s.Name() == "bigtable.OnlineRead" { + r.SpanRecorder.OnEnd(s) + } +} + +var ( + spanRecorderOnce sync.Once + spanRecorder *onlineReadSpanRecorder +) + +// installSpanRecorder installs one SDK tracer provider for the rest of the test process. It is installed +// once and never restored: the package tracer is an otel global delegate, which binds to the first +// provider ever set (global.SetTracerProvider uses a sync.Once), so a provider swapped in per test would +// only be seen by the first test of a -count=N run. +func installSpanRecorder() *onlineReadSpanRecorder { + spanRecorderOnce.Do(func() { + spanRecorder = &onlineReadSpanRecorder{SpanRecorder: tracetest.NewSpanRecorder()} + otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(spanRecorder))) + }) + return spanRecorder +} + +// readSpan runs read under a fresh parent span and returns the bigtable.OnlineRead span it produced. The +// recorder is emptied before returning. +func readSpan(t *testing.T, read func(ctx context.Context)) sdktrace.ReadOnlySpan { + t.Helper() + recorder := installSpanRecorder() + ctx, parent := otel.Tracer("bigtable-test").Start(context.Background(), "test-parent") + traceID := parent.SpanContext().TraceID() + recorder.traces.Store(traceID, struct{}{}) + read(ctx) + parent.End() + recorder.traces.Delete(traceID) + ended := recorder.Ended() + recorder.Reset() + require.Len(t, ended, 1, "one bigtable.OnlineRead span in the trace") + require.Equal(t, parent.SpanContext().SpanID(), ended[0].Parent().SpanID()) + return ended[0] +} + +func spanAttributes(s sdktrace.ReadOnlySpan) map[string]attribute.Value { + out := map[string]attribute.Value{} + for _, kv := range s.Attributes() { + out[string(kv.Key)] = kv.Value + } + return out +} + +func TestBigtableReadSpanAttributes(t *testing.T) { + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(4)}) + keys := userKeys(3) + tableA, tableB := testBigtableFeastProject+".a", testBigtableFeastProject+".b" + e.seedView(t, subscriberTable, "fvA", keys[:2]) + e.seedView(t, subscriberTable, "fvB", keys[:1]) + e.seedView(t, tableA, "fvA", keys) + e.seedView(t, tableB, "fvB", keys[1:]) + tests := []struct { + name string + byView map[string][]string + wantTable string + wantRows int64 + wantErr bool + }{ + // 3 entities x 2 views = 6 row keys in 2 chunks of at most 4; 3 rows exist. + {name: "one table", byView: map[string][]string{"fvA": {"subscriber"}, "fvB": {"subscriber"}}, + wantTable: subscriberTable, wantRows: 3}, + // 3 row keys per table, 1 chunk each; 3 + 2 rows exist. Tables are comma-joined in request order. + {name: "two tables", byView: map[string][]string{"fvA": {"a"}, "fvB": {"b"}}, + wantTable: tableA + "," + tableB, wantRows: 5}, + {name: "error", byView: map[string][]string{"fvA": {"a"}, "fvB": {"never_created"}}, + wantTable: tableA + "," + testBigtableFeastProject + ".never_created", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var err error + span := readSpan(t, func(ctx context.Context) { + _, err = e.store.OnlineReadWithEntities(ctx, keys, []string{"fvA", "fvB"}, []string{"f", "f"}, tt.byView) + }) + attrs := spanAttributes(span) + keysOf := make([]string, 0, len(attrs)) + for k := range attrs { + keysOf = append(keysOf, k) + } + assert.ElementsMatch(t, []string{"bigtable.table", "feast.entity_count", "bigtable.row_keys", + "bigtable.chunk_size", "bigtable.chunks", "bigtable.chunk_rounds", "bigtable.call_slot_wait_ms", + "bigtable.inflight_wait_ms", "bigtable.rows_found"}, keysOf) + assert.Equal(t, tt.wantTable, attrs["bigtable.table"].AsString()) + assert.Equal(t, int64(3), attrs["feast.entity_count"].AsInt64()) + assert.Equal(t, int64(6), attrs["bigtable.row_keys"].AsInt64()) + assert.Equal(t, int64(4), attrs["bigtable.chunk_size"].AsInt64()) + assert.Equal(t, int64(2), attrs["bigtable.chunks"].AsInt64()) + assert.Equal(t, int64(1), attrs["bigtable.chunk_rounds"].AsInt64(), "2 chunks fit 50 slots") + assert.GreaterOrEqual(t, attrs["bigtable.call_slot_wait_ms"].AsFloat64(), 0.0) + assert.GreaterOrEqual(t, attrs["bigtable.inflight_wait_ms"].AsFloat64(), 0.0) + if !tt.wantErr { + require.NoError(t, err) + assert.Equal(t, tt.wantRows, attrs["bigtable.rows_found"].AsInt64()) + assert.Equal(t, otelcodes.Unset, span.Status().Code) + return + } + require.Error(t, err) + assert.Equal(t, otelcodes.Error, span.Status().Code) + assert.Contains(t, span.Status().Description, "never_created") + require.NotEmpty(t, span.Events()) + assert.Equal(t, "exception", span.Events()[0].Name, "RecordError adds an exception event") + }) + } +} + +// durationSamples is the number of observations of the duration histogram under status. +func durationSamples(t *testing.T, status string) uint64 { + t.Helper() + obs, err := bigtableReadDuration.GetMetricWithLabelValues(status) + require.NoError(t, err) + m := &dto.Metric{} + require.NoError(t, obs.(prometheus.Metric).Write(m)) + return m.GetHistogram().GetSampleCount() +} + +// TestBigtableReadMetrics: a call over two tables adds each table's sent chunks and found rows to that +// table's counters and one duration observation under its status; a failed call counts only the chunks +// it sent. The metrics are process-wide, so the test compares before and after. +func TestBigtableReadMetrics(t *testing.T) { + e := newReadEnvWithConfig(t, map[string]interface{}{"keys_per_request": float64(2)}) + keys := userKeys(5) + tableA, tableB := testBigtableFeastProject+".metrics_a", testBigtableFeastProject+".metrics_b" + e.seedView(t, tableA, "fvA", keys[:3]) + e.seedView(t, tableB, "fvB", keys[:1]) + byView := map[string][]string{"fvB": {"metrics_b"}, "fvA": {"metrics_a"}} + counter := func(c *prometheus.CounterVec, table string) float64 { + return testutil.ToFloat64(c.WithLabelValues(table)) + } + chunksA, chunksB := counter(bigtableReadChunks, tableA), counter(bigtableReadChunks, tableB) + rowsA, rowsB := counter(bigtableReadRowsFound, tableA), counter(bigtableReadRowsFound, tableB) + okBefore := durationSamples(t, "ok") + _, err := e.read(keys, []string{"fvB", "fvA"}, []string{"f", "f"}, byView) + require.NoError(t, err) + assert.Equal(t, 3.0, counter(bigtableReadChunks, tableA)-chunksA, "5 keys in chunks of 2") + assert.Equal(t, 3.0, counter(bigtableReadChunks, tableB)-chunksB) + assert.Equal(t, 3.0, counter(bigtableReadRowsFound, tableA)-rowsA) + assert.Equal(t, 1.0, counter(bigtableReadRowsFound, tableB)-rowsB) + assert.Equal(t, okBefore+1, durationSamples(t, "ok")) + + missing := testBigtableFeastProject + ".never_created_metrics" + sentBefore := counter(bigtableReadChunks, missing) + errBefore := durationSamples(t, "error") + _, err = e.read(keys, []string{"fvA"}, []string{"f"}, map[string][]string{"fvA": {"never_created_metrics"}}) + require.Error(t, err) + assert.Equal(t, errBefore+1, durationSamples(t, "error")) + sent := counter(bigtableReadChunks, missing) - sentBefore + assert.GreaterOrEqual(t, sent, 1.0, "the failing chunk was sent") + assert.LessOrEqual(t, sent, 3.0, "no more than the 3 planned") +} diff --git a/go/internal/feast/onlinestore/bigtableonlinestore_test.go b/go/internal/feast/onlinestore/bigtableonlinestore_test.go new file mode 100644 index 00000000000..9abc27e9058 --- /dev/null +++ b/go/internal/feast/onlinestore/bigtableonlinestore_test.go @@ -0,0 +1,556 @@ +package onlinestore + +import ( + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net" + "os" + "strconv" + "testing" + "time" + + btpb "cloud.google.com/go/bigtable/apiv2/bigtablepb" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/api/option" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + + "github.com/feast-dev/feast/go/internal/feast/model" + "github.com/feast-dev/feast/go/internal/feast/registry" + "github.com/feast-dev/feast/go/protos/feast/types" +) + +func TestParseBigtableConfig(t *testing.T) { + // defaults is the config of {"instance": "i"}: chunks of 5 keys, 50 at a time, no store-wide cap. + // read_timeout_ms defaults to 60 s, the Python client's ReadRows retry deadline, so an unset budget + // never lets the client retry without end. + defaults := bigtableConfig{Instance: "i", KeysPerRequest: 5, MaxConcurrentChunks: 50, ReadTimeout: 60 * time.Second} + tests := []struct { + name string + in map[string]interface{} + want bigtableConfig + wantErr string + }{ + {"defaults", map[string]interface{}{"type": "bigtable", "instance": "i"}, defaults, ""}, + {"all set", map[string]interface{}{"instance": "i", "project_id": "p", "app_profile": "serve", + "keys_per_request": float64(25), "max_concurrent_chunks": float64(4), + "read_timeout_ms": float64(150), "max_inflight_reads": float64(300), "max_inflight_wait_ms": float64(15), + "max_versions": float64(2)}, + bigtableConfig{ProjectID: "p", Instance: "i", AppProfile: "serve", KeysPerRequest: 25, + MaxConcurrentChunks: 4, ReadTimeout: 150 * time.Millisecond, MaxInflightReads: 300, + MaxInflightWait: 15 * time.Millisecond}, ""}, + {"int values", map[string]interface{}{"instance": "i", "keys_per_request": 100, "max_versions": 1}, + bigtableConfig{Instance: "i", KeysPerRequest: 100, MaxConcurrentChunks: 50, ReadTimeout: 60 * time.Second}, ""}, + {"missing instance", map[string]interface{}{}, bigtableConfig{}, "instance"}, + {"empty instance", map[string]interface{}{"instance": ""}, bigtableConfig{}, "instance"}, + {"quoted number", map[string]interface{}{"instance": "i", "keys_per_request": "50"}, bigtableConfig{}, "keys_per_request"}, + {"fraction", map[string]interface{}{"instance": "i", "keys_per_request": 2.5}, bigtableConfig{}, "keys_per_request"}, + {"zero", map[string]interface{}{"instance": "i", "max_concurrent_chunks": float64(0)}, bigtableConfig{}, "max_concurrent_chunks"}, + {"negative", map[string]interface{}{"instance": "i", "read_timeout_ms": float64(-1)}, bigtableConfig{}, "read_timeout_ms"}, + {"non-string profile", map[string]interface{}{"instance": "i", "app_profile": float64(1)}, bigtableConfig{}, "app_profile"}, + {"max_versions zero ignored", map[string]interface{}{"instance": "i", "max_versions": float64(0)}, defaults, ""}, + {"max_versions non-number ignored", map[string]interface{}{"instance": "i", "max_versions": "two"}, defaults, ""}, + {"bad max_inflight_reads", map[string]interface{}{"instance": "i", "max_inflight_reads": true}, bigtableConfig{}, "max_inflight_reads"}, + {"zero max_inflight_reads", map[string]interface{}{"instance": "i", "max_inflight_reads": float64(0)}, bigtableConfig{}, "max_inflight_reads"}, + // max_inflight_wait_ms may be 0, which is also its default: a full cap rejects a read at once. + {"zero max_inflight_wait_ms", map[string]interface{}{"instance": "i", "max_inflight_wait_ms": float64(0)}, defaults, ""}, + {"negative max_inflight_wait_ms", map[string]interface{}{"instance": "i", "max_inflight_wait_ms": float64(-1)}, + bigtableConfig{}, "max_inflight_wait_ms must be a non-negative integer"}, + {"fractional max_inflight_wait_ms", map[string]interface{}{"instance": "i", "max_inflight_wait_ms": 2.5}, + bigtableConfig{}, "max_inflight_wait_ms"}, + {"bad max_inflight_wait_ms", map[string]interface{}{"instance": "i", "max_inflight_wait_ms": "10"}, + bigtableConfig{}, "max_inflight_wait_ms"}, + // Keys only the Python SDK uses, and unknown keys, are ignored. + {"other keys ignored", map[string]interface{}{"instance": "i", "write_app_profile": "batch", + "initial_tablets": float64(16), "not_a_setting": true}, defaults, ""}, + // An explicit null (`project_id:`, `read_timeout_ms: null`, or an unset ${VAR} after os.ExpandEnv) + // leaves the default, as Python's Optional fields do. + {"null project_id", map[string]interface{}{"instance": "i", "project_id": nil}, defaults, ""}, + {"null app_profile", map[string]interface{}{"instance": "i", "app_profile": nil}, defaults, ""}, + {"null keys_per_request", map[string]interface{}{"instance": "i", "keys_per_request": nil}, defaults, ""}, + {"null read_timeout_ms", map[string]interface{}{"instance": "i", "read_timeout_ms": nil}, defaults, ""}, + {"null max_concurrent_chunks", map[string]interface{}{"instance": "i", "max_concurrent_chunks": nil}, defaults, ""}, + {"null max_inflight_reads", map[string]interface{}{"instance": "i", "max_inflight_reads": nil}, defaults, ""}, + {"null max_inflight_wait_ms", map[string]interface{}{"instance": "i", "max_inflight_wait_ms": nil}, defaults, ""}, + {"null instance", map[string]interface{}{"instance": nil}, bigtableConfig{}, "instance is required"}, + // adaptive_chunking and disable_metrics are false unless set to a YAML boolean true. + {"switches on", map[string]interface{}{"instance": "i", "adaptive_chunking": true, "disable_metrics": true}, + bigtableConfig{Instance: "i", KeysPerRequest: 5, MaxConcurrentChunks: 50, ReadTimeout: 60 * time.Second, + AdaptiveChunking: true, DisableMetrics: true}, ""}, + {"switches off", map[string]interface{}{"instance": "i", "adaptive_chunking": false, "disable_metrics": false}, + defaults, ""}, + {"null adaptive_chunking", map[string]interface{}{"instance": "i", "adaptive_chunking": nil}, defaults, ""}, + {"null disable_metrics", map[string]interface{}{"instance": "i", "disable_metrics": nil}, defaults, ""}, + {"quoted disable_metrics", map[string]interface{}{"instance": "i", "disable_metrics": "false"}, + bigtableConfig{}, "disable_metrics must be true or false"}, + {"quoted adaptive_chunking", map[string]interface{}{"instance": "i", "adaptive_chunking": "true"}, + bigtableConfig{}, "adaptive_chunking must be true or false"}, + {"numeric disable_metrics", map[string]interface{}{"instance": "i", "disable_metrics": float64(1)}, + bigtableConfig{}, "disable_metrics must be true or false"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseBigtableConfig(tt.in) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// bigtableFixtures mirrors testdata/bigtable_fixtures.json, written by the Python generator +// testdata/gen_bigtable_fixtures.py from the in-tree Python BigtableOnlineStore. A Python unit test +// (test_bigtable_go_fixtures.py) fails when the committed file no longer matches what Python writes. +type bigtableFixtures struct { + TableNames []struct { + Project string `json:"project"` + Entities []string `json:"entities"` + Want string `json:"want"` + } `json:"table_names"` + RowKeys []struct { + Name string `json:"name"` + Entityless bool `json:"entityless"` + JoinKeys []string `json:"join_keys"` + Values []struct { + Type string `json:"type"` + Value string `json:"value"` + } `json:"values"` + View string `json:"view"` + Want *string `json:"want"` + } `json:"row_keys"` + Cells []struct { + Name string `json:"name"` + ValueB64 string `json:"value_b64"` + EventTS string `json:"event_ts"` + WantSeconds int64 `json:"want_seconds"` + WantNanos int32 `json:"want_nanos"` + WantValue json.RawMessage `json:"want_value"` + } `json:"cells"` + MurmurVectors []struct { + Length int `json:"length"` + Want string `json:"want"` + } `json:"murmur_vectors"` +} + +func loadBigtableFixtures(t *testing.T) bigtableFixtures { + t.Helper() + raw, err := os.ReadFile("testdata/bigtable_fixtures.json") + require.NoError(t, err) + var f bigtableFixtures + require.NoError(t, json.Unmarshal(raw, &f)) + require.NotEmpty(t, f.TableNames) + require.NotEmpty(t, f.RowKeys) + require.NotEmpty(t, f.Cells) + require.NotEmpty(t, f.MurmurVectors) + return f +} + +// fixtureValue builds a types.Value from the generator's {type, value} encoding: bytes are base64, +// integers are decimal strings, strings and uuids are as-is. +func fixtureValue(typ, value string) (*types.Value, error) { + switch typ { + case "string": + return &types.Value{Val: &types.Value_StringVal{StringVal: value}}, nil + case "uuid": + return &types.Value{Val: &types.Value_UuidVal{UuidVal: value}}, nil + case "bytes": + b, err := base64.StdEncoding.DecodeString(value) + return &types.Value{Val: &types.Value_BytesVal{BytesVal: b}}, err + case "int32": + n, err := strconv.ParseInt(value, 10, 32) + return &types.Value{Val: &types.Value_Int32Val{Int32Val: int32(n)}}, err + case "int64": + n, err := strconv.ParseInt(value, 10, 64) + return &types.Value{Val: &types.Value_Int64Val{Int64Val: n}}, err + } + return nil, fmt.Errorf("unknown fixture value type %q", typ) +} + +func TestBigtableTableNameParity(t *testing.T) { + for _, tc := range loadBigtableFixtures(t).TableNames { + t.Run(fmt.Sprintf("%s/%v", tc.Project, tc.Entities), func(t *testing.T) { + got := bigtableTableName(tc.Project, tc.Entities) + assert.Equal(t, tc.Want, got) + assert.LessOrEqual(t, len([]rune(got)), bigtableTableNameMaxLength) + }) + } +} + +func TestBigtableRowKeyParity(t *testing.T) { + entityless := 0 + for _, tc := range loadBigtableFixtures(t).RowKeys { + if tc.Entityless { + entityless++ + } + t.Run(tc.Name, func(t *testing.T) { + key := &types.EntityKey{JoinKeys: tc.JoinKeys} + for _, v := range tc.Values { + val, err := fixtureValue(v.Type, v.Value) + require.NoError(t, err) + key.EntityValues = append(key.EntityValues, val) + } + if tc.Entityless { + // The generator built this key from Python's DUMMY_ENTITY_ID / DUMMY_ENTITY_VAL; they must + // be what the Go model uses. + assert.Equal(t, []string{model.DUMMY_ENTITY_ID}, tc.JoinKeys) + assert.True(t, proto.Equal(&model.DUMMY_ENTITY_VALUE, key.EntityValues[0])) + } + got, err := bigtableRowKey(key, tc.View, 3) + if tc.Want == nil { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, *tc.Want, got) + // Serving builds row keys in rowTargets from the entity hash; it must give the same key. + hash, err := bigtableEntityHash(key, 3) + require.NoError(t, err) + assert.Equal(t, *tc.Want, bigtableRowKeyFromHash(hash, tc.View)) + _, served := (&bigtableTableRead{views: []*bigtableViewRead{{name: tc.View}}}).rowTargets([]string{hash}) + assert.Equal(t, []string{*tc.Want}, []string(served), "the row key serving reads") + }) + } + assert.Equal(t, 1, entityless, "fixture must have one entityless row key") +} + +func TestNormalizeSerializationVersion(t *testing.T) { + tests := []struct { + in, want int64 + wantErr bool + }{ + {0, 3, false}, + {3, 3, false}, + {1, 0, true}, + {2, 0, true}, + } + for _, tt := range tests { + t.Run(strconv.FormatInt(tt.in, 10), func(t *testing.T) { + got, err := normalizeSerializationVersion(tt.in) + if tt.wantErr { + require.ErrorContains(t, err, "entity_key_serialization_version") + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestParseEventTS(t *testing.T) { + tenUTC := time.Date(2026, 11, 17, 10, 0, 0, 0, time.UTC) + tests := []struct { + in string + want time.Time + wantErr bool + }{ + {"2026-11-17T10:00:00.123456+00:00", tenUTC.Add(123456 * time.Microsecond), false}, + {"2026-11-17T10:00:00+00:00", tenUTC, false}, + {"2026-11-17T15:30:00+05:30", tenUTC, false}, + {"2026-11-17T15:53:28+05:53:28", tenUTC, false}, // offset with seconds, as isoformat writes it + {"2026-11-17T04:06:31.5-05:53:29", tenUTC.Add(500 * time.Millisecond), false}, + {"2026-11-17T10:00:00", tenUTC, false}, // naive reads as UTC + {"garbage", time.Time{}, true}, + {"", time.Time{}, true}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + got, err := parseEventTS([]byte(tt.in)) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want.Unix(), got.GetSeconds()) + assert.Equal(t, int32(tt.want.Nanosecond()), got.GetNanos()) + }) + } + got, err := parseEventTS([]byte("2026-11-17T10:00:00.123456+00:00")) + require.NoError(t, err) + assert.Equal(t, int64(1794909600), got.GetSeconds()) + assert.Equal(t, int32(123456000), got.GetNanos()) +} + +// TestBigtableCellFixtures checks that Go reads the cells Python writes: each event_ts gives Python's +// epoch seconds and nanos, and each serialized value decodes to the value Python recorded as JSON. +func TestBigtableCellFixtures(t *testing.T) { + for _, tc := range loadBigtableFixtures(t).Cells { + t.Run(tc.Name, func(t *testing.T) { + ts, err := parseEventTS([]byte(tc.EventTS)) + require.NoError(t, err) + assert.Equal(t, tc.WantSeconds, ts.GetSeconds()) + assert.Equal(t, tc.WantNanos, ts.GetNanos()) + + raw, err := base64.StdEncoding.DecodeString(tc.ValueB64) + require.NoError(t, err) + var got, want types.Value + require.NoError(t, proto.Unmarshal(raw, &got)) + require.NoError(t, protojson.Unmarshal(tc.WantValue, &want)) + assert.True(t, proto.Equal(&want, &got), "got %v, want %v", &got, &want) + }) + } +} + +func TestResolveProjectID(t *testing.T) { + adcErr := errors.New("no credentials") + tests := []struct { + name string + configured string + envProject string // GOOGLE_CLOUD_PROJECT + envLegacy string // GCLOUD_PROJECT + found string + findErr error + want string + wantFind bool + wantErr string + }{ + {name: "configured wins", configured: "p", envProject: "env", envLegacy: "legacy", found: "adc", want: "p"}, + {name: "GOOGLE_CLOUD_PROJECT before credentials", envProject: "env", envLegacy: "legacy", found: "adc", + want: "env"}, + {name: "GCLOUD_PROJECT before credentials", envLegacy: "legacy", found: "adc", want: "legacy"}, + {name: "falls back to credentials", found: "adc", want: "adc", wantFind: true}, + {name: "all empty", wantFind: true, wantErr: "GOOGLE_CLOUD_PROJECT"}, + {name: "credentials error", findErr: adcErr, wantFind: true, wantErr: "project_id"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("GOOGLE_CLOUD_PROJECT", tt.envProject) + t.Setenv("GCLOUD_PROJECT", tt.envLegacy) + called := false + find := func(context.Context) (string, error) { + called = true + return tt.found, tt.findErr + } + got, err := resolveProjectID(context.Background(), tt.configured, find) + assert.Equal(t, tt.wantFind, called, "find called") + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + if tt.findErr != nil { + assert.ErrorIs(t, err, tt.findErr) + } + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestTolerableStartupPingError(t *testing.T) { + tests := []struct { + name string + err error + emulator bool + want bool + }{ + {"NotFound (empty instance)", status.Error(codes.NotFound, "No tables found for instance"), false, true}, + {"NotFound wrapped", fmt.Errorf("ping: %w", status.Error(codes.NotFound, "x")), false, true}, + {"Unimplemented on an emulator", status.Error(codes.Unimplemented, "x"), true, true}, + {"Unimplemented on real Bigtable", status.Error(codes.Unimplemented, "x"), false, false}, + {"PermissionDenied", status.Error(codes.PermissionDenied, "x"), false, false}, + {"Unauthenticated", status.Error(codes.Unauthenticated, "x"), true, false}, + {"DeadlineExceeded", status.Error(codes.DeadlineExceeded, "x"), false, false}, + {"context deadline", context.DeadlineExceeded, false, false}, + {"not a status error", errors.New("dial failed"), false, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reason, ok := tolerableStartupPingError(tt.err, tt.emulator) + assert.Equal(t, tt.want, ok) + assert.Equal(t, tt.want, reason != "", "a reason exactly when tolerated") + }) + } +} + +// pingAnswerServer is a Bigtable data server whose PingAndWarm returns code; every other RPC is +// unimplemented. +type pingAnswerServer struct { + btpb.UnimplementedBigtableServer + code codes.Code +} + +func (s *pingAnswerServer) PingAndWarm(context.Context, *btpb.PingAndWarmRequest) (*btpb.PingAndWarmResponse, error) { + return nil, status.Error(s.code, "test answer") +} + +// TestNewBigtableOnlineStoreStartupPingAnswers runs the constructor against a server whose PingAndWarm +// fails with each code, with BIGTABLE_EMULATOR_HOST set as for any emulator. The "real Bigtable" side of +// Unimplemented is covered by TestTolerableStartupPingError: without the emulator variable the client +// would start its Cloud Monitoring exporter. +func TestNewBigtableOnlineStoreStartupPingAnswers(t *testing.T) { + tests := []struct { + code codes.Code + wantStart bool + }{ + {codes.NotFound, true}, + {codes.Unimplemented, true}, + {codes.PermissionDenied, false}, + {codes.Unauthenticated, false}, + } + for _, tt := range tests { + t.Run(tt.code.String(), func(t *testing.T) { + lis, err := net.Listen("tcp", "localhost:0") + require.NoError(t, err) + srv := grpc.NewServer() + btpb.RegisterBigtableServer(srv, &pingAnswerServer{code: tt.code}) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + t.Setenv("BIGTABLE_EMULATOR_HOST", lis.Addr().String()) + conn, err := grpc.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + + cfg := mustParseBigtableConfig(t, map[string]interface{}{"instance": "i", "project_id": "p"}) + store, err := newBigtableOnlineStore(context.Background(), "feast", ®istry.RepoConfig{}, cfg, + 5*time.Second, option.WithGRPCConn(conn)) + if !tt.wantStart { + require.ErrorContains(t, err, "PingAndWarm") + assert.Equal(t, tt.code, status.Code(err)) + assert.Nil(t, store) + return + } + require.NoError(t, err) + require.NotNil(t, store) + store.Destruct() + }) + } +} + +func TestNewBigtableOnlineStoreAgainstBttest(t *testing.T) { + store, _, _ := newTestBigtable(t, map[string]interface{}{"instance": "i", "project_id": "p"}) + require.NotNil(t, store) + assert.Equal(t, testBigtableFeastProject, store.project) + assert.Equal(t, int64(bigtableSerializationVersion), store.serializationVersion) + assert.Same(t, store.table("t"), store.table("t"), "table handles are cached") + + _, err := store.OnlineRead(context.Background(), nil, nil, nil) + require.ErrorIs(t, err, errors.ErrUnsupported) + + assert.NotPanics(t, store.Destruct) + assert.NotPanics(t, store.Destruct) +} + +func TestNewBigtableOnlineStoreRejectsOldSerialization(t *testing.T) { + cfg := map[string]interface{}{"type": "bigtable", "instance": "i", "project_id": "p"} + repoConfig := ®istry.RepoConfig{Project: "feast", OnlineStore: cfg, EntityKeySerializationVersion: 2} + _, err := NewBigtableOnlineStore(repoConfig.Project, repoConfig, cfg) + require.ErrorContains(t, err, "entity_key_serialization_version") +} + +// TestNewBigtableOnlineStoreStartupTimeout points the store at a TCP listener that accepts connections +// and never speaks gRPC, so PingAndWarm can only end by the startup timeout. +func TestNewBigtableOnlineStoreStartupTimeout(t *testing.T) { + lis, err := net.Listen("tcp", "localhost:0") + require.NoError(t, err) + t.Setenv("BIGTABLE_EMULATOR_HOST", lis.Addr().String()) // no built-in metrics exporter + accepted := make(chan []net.Conn, 1) + go func() { + var conns []net.Conn + for { + c, err := lis.Accept() + if err != nil { + accepted <- conns + return + } + conns = append(conns, c) + } + }() + t.Cleanup(func() { + _ = lis.Close() + for _, c := range <-accepted { + _ = c.Close() + } + }) + conn, err := grpc.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + + cfg := mustParseBigtableConfig(t, map[string]interface{}{"instance": "i", "project_id": "p"}) + type result struct { + store *BigtableOnlineStore + err error + } + done := make(chan result, 1) + start := time.Now() + go func() { + s, err := newBigtableOnlineStore(context.Background(), "feast", ®istry.RepoConfig{}, cfg, + 200*time.Millisecond, option.WithGRPCConn(conn)) + done <- result{s, err} + }() + select { + case r := <-done: + require.ErrorContains(t, r.err, "PingAndWarm") + assert.Nil(t, r.store) + assert.Less(t, time.Since(start), 2*time.Second) + case <-time.After(2 * time.Second): + t.Fatal("constructor did not return within 2s of a 200ms startup timeout") + } +} + +// TestBigtableConfigValidate: validate rejects settings that would break reads (slices.Chunk panics on a +// zero size, a zero-capacity slot channel blocks forever, a negative channel size panics, and Bigtable +// takes at most 100 keys per request), and the constructor runs it before creating a client. +func TestBigtableConfigValidate(t *testing.T) { + valid := mustParseBigtableConfig(t, map[string]interface{}{"instance": "i", "project_id": "p"}) + require.NoError(t, valid.validate()) + tests := []struct { + name string + edit func(*bigtableConfig) + wantErr string + }{ + {"zero keys_per_request", func(c *bigtableConfig) { c.KeysPerRequest = 0 }, "keys_per_request must be between 1 and 100, got 0"}, + {"keys_per_request over 100", func(c *bigtableConfig) { c.KeysPerRequest = 101 }, "keys_per_request must be between 1 and 100, got 101"}, + {"zero max_concurrent_chunks", func(c *bigtableConfig) { c.MaxConcurrentChunks = 0 }, "max_concurrent_chunks must be positive, got 0"}, + {"zero read timeout", func(c *bigtableConfig) { c.ReadTimeout = 0 }, "read_timeout_ms must be positive, got 0"}, + {"negative max_inflight_reads", func(c *bigtableConfig) { c.MaxInflightReads = -1 }, "max_inflight_reads must not be negative, got -1"}, + {"negative max_inflight_wait_ms", func(c *bigtableConfig) { c.MaxInflightWait = -time.Millisecond }, "max_inflight_wait_ms must not be negative, got -1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := valid + tt.edit(&cfg) + require.ErrorContains(t, cfg.validate(), tt.wantErr) + s, err := newBigtableOnlineStore(context.Background(), "feast", ®istry.RepoConfig{}, cfg, time.Second) + require.ErrorContains(t, err, tt.wantErr) + assert.Nil(t, s) + }) + } + over, err := parseBigtableConfig(map[string]interface{}{"instance": "i", "keys_per_request": float64(101)}) + require.NoError(t, err, "parse reads the value; validate rejects it") + require.ErrorContains(t, over.validate(), "keys_per_request") +} + +func TestNewOnlineStoreBigtableType(t *testing.T) { + _, err := NewOnlineStore(®istry.RepoConfig{ + Project: "feast", + OnlineStore: map[string]interface{}{"type": "bigtable"}, + }) + require.ErrorContains(t, err, "instance") +} + +// TestBigtableMurmurHashVectors: the entity-id hash matches Python's mmh3.hash_bytes(bytes(range(n))) +// for every length 1 to 100, which covers every 16-byte tail size and several full blocks. +func TestBigtableMurmurHashVectors(t *testing.T) { + vectors := loadBigtableFixtures(t).MurmurVectors + require.Len(t, vectors, 100) + for i, v := range vectors { + require.Equal(t, i+1, v.Length) + data := make([]byte, v.Length) + for j := range data { + data[j] = byte(j) + } + got := bigtableMurmurHash(data) + assert.Equal(t, v.Want, hex.EncodeToString(got[:]), "length %d", v.Length) + } +} diff --git a/go/internal/feast/onlinestore/onlinestore.go b/go/internal/feast/onlinestore/onlinestore.go index 837a3f31d82..4281b847f13 100644 --- a/go/internal/feast/onlinestore/onlinestore.go +++ b/go/internal/feast/onlinestore/onlinestore.go @@ -10,8 +10,12 @@ import ( "github.com/feast-dev/feast/go/protos/feast/serving" "github.com/feast-dev/feast/go/protos/feast/types" "github.com/golang/protobuf/ptypes/timestamp" + "go.opentelemetry.io/otel" ) +// tracer is the OpenTelemetry tracer shared by the online stores in this package. +var tracer = otel.Tracer("github.com/feast-dev/feast/go/onlinestore") + type FeatureData struct { Reference serving.FeatureReferenceV2 Timestamp timestamp.Timestamp @@ -43,6 +47,17 @@ type OnlineStore interface { Destruct() } +// EntityAwareOnlineStore is implemented by stores that need each feature view's +// entity names to locate data, such as Bigtable, which names tables by entity set. +type EntityAwareOnlineStore interface { + // OnlineReadWithEntities is OnlineRead plus entityNamesByView, which maps each requested feature + // view's base name to that view's entity names ("__dummy" for an entityless view). Otherwise its + // arguments, result and errors have the same semantics as OnlineRead. + OnlineReadWithEntities(ctx context.Context, entityKeys []*types.EntityKey, + featureViewNames []string, featureNames []string, + entityNamesByView map[string][]string) ([][]FeatureData, error) +} + func getOnlineStoreType(onlineStoreConfig map[string]interface{}) (string, bool) { if onlineStoreType, ok := onlineStoreConfig["type"]; !ok { // If online store type isn't specified, default to sqlite @@ -53,6 +68,8 @@ func getOnlineStoreType(onlineStoreConfig map[string]interface{}) (string, bool) } } +// NewOnlineStore returns the online store named by the online_store type in config: sqlite, redis, +// dynamodb, postgres or bigtable. func NewOnlineStore(config *registry.RepoConfig) (OnlineStore, error) { onlineStoreType, ok := getOnlineStoreType(config.OnlineStore) if !ok { @@ -69,8 +86,14 @@ func NewOnlineStore(config *registry.RepoConfig) (OnlineStore, error) { } else if onlineStoreType == "postgres" { onlineStore, err := NewPostgresOnlineStore(config.Project, config, config.OnlineStore) return onlineStore, err + } else if onlineStoreType == "bigtable" { + onlineStore, err := NewBigtableOnlineStore(config.Project, config, config.OnlineStore) + if err != nil { + return nil, err // not a typed nil inside the interface + } + return onlineStore, nil } else { - return nil, fmt.Errorf("%s online store type is currently not supported; only redis, sqlite, dynamodb, and postgres are supported", onlineStoreType) + return nil, fmt.Errorf("%s online store type is currently not supported; only redis, sqlite, dynamodb, postgres, and bigtable are supported", onlineStoreType) } } diff --git a/go/internal/feast/onlinestore/redisonlinestore.go b/go/internal/feast/onlinestore/redisonlinestore.go index d4e3741d0da..42c4943bd00 100644 --- a/go/internal/feast/onlinestore/redisonlinestore.go +++ b/go/internal/feast/onlinestore/redisonlinestore.go @@ -11,7 +11,6 @@ import ( "strings" "github.com/feast-dev/feast/go/internal/feast/registry" - "go.opentelemetry.io/otel" "github.com/redis/go-redis/v9" "github.com/spaolacci/murmur3" @@ -24,8 +23,6 @@ import ( //redistrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/redis/go-redis.v9" ) -var tracer = otel.Tracer("github.com/feast-dev/feast/go/onlinestore") - type redisType int const ( diff --git a/go/internal/feast/onlinestore/testdata/bigtable_fixtures.json b/go/internal/feast/onlinestore/testdata/bigtable_fixtures.json new file mode 100644 index 00000000000..15e838ee1c8 --- /dev/null +++ b/go/internal/feast/onlinestore/testdata/bigtable_fixtures.json @@ -0,0 +1,661 @@ +{ + "cells": [ + { + "event_ts": "2026-11-17T10:00:00.123456+00:00", + "name": "int64", + "value_b64": "IP/////////v/wE=", + "want_nanos": 123456000, + "want_seconds": 1794909600, + "want_value": { + "int64_val": "-9007199254740993" + } + }, + { + "event_ts": "2026-11-17T10:00:00+00:00", + "name": "double", + "value_b64": "KZqZmZmZmbk/", + "want_nanos": 0, + "want_seconds": 1794909600, + "want_value": { + "double_val": 0.1 + } + }, + { + "event_ts": "2026-11-17T15:30:00.250000+05:30", + "name": "string", + "value_b64": "Egrml6XmnKwgYWJj", + "want_nanos": 250000000, + "want_seconds": 1794909600, + "want_value": { + "string_val": "日本 abc" + } + }, + { + "event_ts": "2026-11-17T10:00:00+00:00", + "name": "bool", + "value_b64": "OAE=", + "want_nanos": 0, + "want_seconds": 1794909600, + "want_value": { + "bool_val": true + } + }, + { + "event_ts": "2026-11-17T10:00:00.123456+00:00", + "name": "float list", + "value_b64": "ggEOCgwAAAA/AACgvwAAQEA=", + "want_nanos": 123456000, + "want_seconds": 1794909600, + "want_value": { + "float_list_val": { + "val": [ + 0.5, + -1.25, + 3.0 + ] + } + } + }, + { + "event_ts": "2026-11-17T10:00:00+00:00", + "name": "null", + "value_b64": "", + "want_nanos": 0, + "want_seconds": 1794909600, + "want_value": {} + } + ], + "murmur_vectors": [ + { + "length": 1, + "want": "b55cff6ee5ab10468335f878aa2d6251" + }, + { + "length": 2, + "want": "4c26ab8dc5f5b37c44e0c26e32013cf0" + }, + { + "length": 3, + "want": "bee653ef2fa172b8b696b352c25562fb" + }, + { + "length": 4, + "want": "10afdf0dae94c5e1e2fdc213bd05d6d3" + }, + { + "length": 5, + "want": "3640f9a6d48cee41f6230c635e15d0f8" + }, + { + "length": 6, + "want": "3c04f5a4bb3a9866a02c51160b24e057" + }, + { + "length": 7, + "want": "680d4bca87694cbd87c725bdd4dd3a61" + }, + { + "length": 8, + "want": "c82f8ed6bde1a747c7dc31ec02eee660" + }, + { + "length": 9, + "want": "322d816e0fcbb4fbb9ff00021d75de78" + }, + { + "length": 10, + "want": "63e4589ee825cacf7620ad72c4134325" + }, + { + "length": 11, + "want": "884f56c7474f7bc5b01b71208dea6569" + }, + { + "length": 12, + "want": "caa51292e6a75db34653f7ec46f17580" + }, + { + "length": 13, + "want": "c2415fc5f2d9524bfcd8a6af9e86ff84" + }, + { + "length": 14, + "want": "646d9035ee33a95fdfc90f387325780d" + }, + { + "length": 15, + "want": "e92549fd98152347e97dc688ee6d84cd" + }, + { + "length": 16, + "want": "303f9091b524494445e82f76566490ab" + }, + { + "length": 17, + "want": "0ec2e79f0ff4765c24a8da9e6b025fc1" + }, + { + "length": 18, + "want": "7bc4e9bad1e448165febb90b188426ce" + }, + { + "length": 19, + "want": "6301a36455a465a6dc1faebf60794f95" + }, + { + "length": 20, + "want": "4b9536577053d2a37a9c7b6c25061f5a" + }, + { + "length": 21, + "want": "0312d428a03dd1cdcbe7a22dfc0ec56b" + }, + { + "length": 22, + "want": "712ac127bff3f84562561e6073a33017" + }, + { + "length": 23, + "want": "db8135156f37a1b941492ab4931c4526" + }, + { + "length": 24, + "want": "dedfb27562844e73529efbbbab7e7094" + }, + { + "length": 25, + "want": "cb82e92eb57cbe3bfc9fefbe3354d3a2" + }, + { + "length": 26, + "want": "726f2202fedc15a5787dc4fcdc680c2e" + }, + { + "length": 27, + "want": "ed2e594d8802161119b51ddc48197428" + }, + { + "length": 28, + "want": "3c8105ee62ff14dc8bcb6745bb502066" + }, + { + "length": 29, + "want": "1acf1815b194e4aa76e1cf8cf7129e64" + }, + { + "length": 30, + "want": "e301a2380d0869f0196bd2e37f68f322" + }, + { + "length": 31, + "want": "94d02ca3e1d33d05905400b4ef9ae59e" + }, + { + "length": 32, + "want": "0f502fb622906dc65111c3346e0a051c" + }, + { + "length": 33, + "want": "1246bafa1b28417d0ba3d6a77380ac55" + }, + { + "length": 34, + "want": "c37dba8a273f51b0c2ea8703f617bed9" + }, + { + "length": 35, + "want": "cea7543bc072117910403edae512d8bc" + }, + { + "length": 36, + "want": "303656299a05332052bfd5bd6a3ec2d9" + }, + { + "length": 37, + "want": "20d802dd5ead7451b0cd03c799538480" + }, + { + "length": 38, + "want": "14cb167d5b641b681a1fa0bf98bf121e" + }, + { + "length": 39, + "want": "c0a0ad8bf4cc60196735a175955a2f1b" + }, + { + "length": 40, + "want": "64808c41d854a0c3ad124c9730ca01a0" + }, + { + "length": 41, + "want": "4a3fd94451243f9a43caace2963fdd58" + }, + { + "length": 42, + "want": "097fa343c1f43479f10bb0eac7d90747" + }, + { + "length": 43, + "want": "ab6ebc119308481c90874831f5a2474d" + }, + { + "length": 44, + "want": "6de08d6274a28b944f56c19a9c58e3c2" + }, + { + "length": 45, + "want": "4fb3c0d4f4b12e56b7abf2cc11e5be8a" + }, + { + "length": 46, + "want": "6492f9713c1bd060955e5a53f5872bfc" + }, + { + "length": 47, + "want": "82489b087c630f8a8c856ed941659776" + }, + { + "length": 48, + "want": "f427780c64bc724fb68004a283e1ea29" + }, + { + "length": 49, + "want": "1718d6854af8f3cbd96b24f5727022ed" + }, + { + "length": 50, + "want": "854d3e9b4941d5e0c1fea22a03bd9827" + }, + { + "length": 51, + "want": "51b58b4875fcdb4818bda421b7c2402f" + }, + { + "length": 52, + "want": "790f3f3292cc8536e97fdb44adef2ac4" + }, + { + "length": 53, + "want": "f6afcd4d98e5bad3acdf67d860bf7ab2" + }, + { + "length": 54, + "want": "389006177c26de075a4f127094c663b9" + }, + { + "length": 55, + "want": "d9370c9f6414d1bc3167463e97694b69" + }, + { + "length": 56, + "want": "94a3e130cd4d862d28dd2498c24686f0" + }, + { + "length": 57, + "want": "ae353e611680ace76510a83fffd9dba3" + }, + { + "length": 58, + "want": "cf20b0d667b9d0dbddcc0f893c128014" + }, + { + "length": 59, + "want": "66194f212d8c54e657c4b6e424df1fab" + }, + { + "length": 60, + "want": "3f928f4f776d999835e2f93bbbb5d716" + }, + { + "length": 61, + "want": "e0cc7063828430317916b12673141b42" + }, + { + "length": 62, + "want": "c55348616be11b15130b5047d22043ce" + }, + { + "length": 63, + "want": "94600734460da3996743c2d4a1c6a4ed" + }, + { + "length": 64, + "want": "0123818d2d52d5ffa18e3356eb3822a2" + }, + { + "length": 65, + "want": "e21e984d019136d08efc5b38b08258bd" + }, + { + "length": 66, + "want": "7c9e1dd63941e1063a9e93229666238d" + }, + { + "length": 67, + "want": "49480147227febbe49aba20df019763e" + }, + { + "length": 68, + "want": "204a8850fb9b9c07f18edfb87af6bd19" + }, + { + "length": 69, + "want": "4497908ab1e7fd47ffcc8a4269abe27b" + }, + { + "length": 70, + "want": "4dd51e8f8e049e8cb4030de90d639347" + }, + { + "length": 71, + "want": "11e666a3d92d07a6cd787180d087629d" + }, + { + "length": 72, + "want": "8ce201e0b7211d2ac92b351123fd9e48" + }, + { + "length": 73, + "want": "baa92b6d0549fcf87c2d6c1b9a877a8e" + }, + { + "length": 74, + "want": "423e702fe96fe3c7e10ffd292323041e" + }, + { + "length": 75, + "want": "036e0f5d2020c43c696c03deec7c9bcd" + }, + { + "length": 76, + "want": "775db669da88d360fa7bd1a221e1a355" + }, + { + "length": 77, + "want": "c34884f896200ae9fe5e591e56166c53" + }, + { + "length": 78, + "want": "5d5cb4c462389c8e76518fa14f7412ac" + }, + { + "length": 79, + "want": "c3dd431f6b5dd6057d49cf0428e9b334" + }, + { + "length": 80, + "want": "0997f69cdb2ed62e7c167e264fc03faa" + }, + { + "length": 81, + "want": "1cb2bed5156195791d6475863ac6fbbe" + }, + { + "length": 82, + "want": "120bf47cb8b8c668d2150b0c164e8d1b" + }, + { + "length": 83, + "want": "d99403f4f5d1057b51eb00d5a0627ea9" + }, + { + "length": 84, + "want": "3c2f3d9e9068676bce02661c51779c33" + }, + { + "length": 85, + "want": "50ad60ed9e7c5b401bead39e2724c195" + }, + { + "length": 86, + "want": "24cc39dd27ad15df930c3243804df743" + }, + { + "length": 87, + "want": "ea514c5a83ac523656961bf694ab5610" + }, + { + "length": 88, + "want": "936cb193bc31674b561b208b64a11851" + }, + { + "length": 89, + "want": "3d729ae9793778cd783ae9a20ad65a6f" + }, + { + "length": 90, + "want": "8f913d394ad9b671ed1bc9001bbc11b8" + }, + { + "length": 91, + "want": "93412794f307e6b189d9b225bdd7eeef" + }, + { + "length": 92, + "want": "44e9ef963fb34da1e5fbb980b01e7a8f" + }, + { + "length": 93, + "want": "443b71687292917dc549c597d1861b16" + }, + { + "length": 94, + "want": "2579ecc5d482c85bb143054e69650be3" + }, + { + "length": 95, + "want": "c8f83054f11ccc1b847e316b128e0eb4" + }, + { + "length": 96, + "want": "30cd1cdc838f936a9b83244bbf522a10" + }, + { + "length": 97, + "want": "4523549dc435bfc105157dae86069761" + }, + { + "length": 98, + "want": "0d14a95abaadec3582db39b8ec39ccd1" + }, + { + "length": 99, + "want": "f847fbe9eacc541d0426e9fa6331169f" + }, + { + "length": 100, + "want": "ca5140c199996fb0990734c8936dbd0f" + } + ], + "row_keys": [ + { + "entityless": false, + "join_keys": [ + "subscriber_id" + ], + "name": "string", + "values": [ + { + "type": "string", + "value": "abc" + } + ], + "view": "subscriber_features", + "want": "3680bb2ca1b2aadf6721b18444692de5#subscriber_features" + }, + { + "entityless": false, + "join_keys": [ + "subscriber_id" + ], + "name": "utf8 string", + "values": [ + { + "type": "string", + "value": "日本" + } + ], + "view": "subscriber_features", + "want": "b889131ec7da658bdebd39b4d65216a0#subscriber_features" + }, + { + "entityless": false, + "join_keys": [ + "blob_id" + ], + "name": "bytes", + "values": [ + { + "type": "bytes", + "value": "AP8=" + } + ], + "view": "blob_features", + "want": "bc6521bcc44c87696cabe33fccfebf73#blob_features" + }, + { + "entityless": false, + "join_keys": [ + "region_id" + ], + "name": "int32", + "values": [ + { + "type": "int32", + "value": "-7" + } + ], + "view": "region_features", + "want": "b1fa50b3137291b300d7a1f3bea9229a#region_features" + }, + { + "entityless": false, + "join_keys": [ + "title_id" + ], + "name": "int64", + "values": [ + { + "type": "int64", + "value": "-9007199254740993" + } + ], + "view": "title_features", + "want": "8bba07fdaec21c2ce9802e79cd535b15#title_features" + }, + { + "entityless": false, + "join_keys": [ + "title_id", + "subscriber_id" + ], + "name": "two join keys reversed", + "values": [ + { + "type": "int64", + "value": "42" + }, + { + "type": "string", + "value": "abc" + } + ], + "view": "subscriber_title_features", + "want": "2242659419ce841affa0e20000b71b9e#subscriber_title_features" + }, + { + "entityless": true, + "join_keys": [ + "__dummy_id" + ], + "name": "entityless", + "values": [ + { + "type": "string", + "value": "" + } + ], + "view": "global_stats", + "want": "de92cd1db280c7aa956cd0b5fe07eb08#global_stats" + }, + { + "entityless": false, + "join_keys": [ + "session_id" + ], + "name": "uuid", + "values": [ + { + "type": "uuid", + "value": "0b3e7c1a-6a2f-4c55-9f4e-1d2c3b4a5f60" + } + ], + "view": "session_features", + "want": null + } + ], + "table_names": [ + { + "entities": [ + "subscriber" + ], + "project": "my_project", + "want": "my_project.subscriber" + }, + { + "entities": [ + "title", + "subscriber" + ], + "project": "my_project", + "want": "my_project.subscriber-title" + }, + { + "entities": [ + "subscriber_profile_region" + ], + "project": "my_project", + "want": "my_project.ff4e7d632471dd16412719b6" + }, + { + "entities": [ + "日本語日本語日本語日本" + ], + "project": "my_project", + "want": "my_project.日本語日本語日本語日本" + }, + { + "entities": [ + "subscriber" + ], + "project": "my_feature_store_project_with_a_deliberately_long_name_00060", + "want": "my_feature_6f3951da94e0544434b8f7d1f3e0.subscriber" + }, + { + "entities": [ + "title" + ], + "project": "my_feature_store_project_with_a_deliberately_long_name_00060", + "want": "my_feature_6f3951da94e0544434b8f7d1f3e0792b.title" + }, + { + "entities": [ + "t" + ], + "project": "my_feature_store_project_with_a_deliberately_long_name_00060", + "want": "my_feature_6f3951da94e0544434b8f7d1f3e0792b.t" + }, + { + "entities": [], + "project": "my_project", + "want": "my_project.__dummy" + }, + { + "entities": [ + "__dummy" + ], + "project": "my_project", + "want": "my_project.__dummy" + } + ] +} diff --git a/go/internal/feast/onlinestore/testdata/gen_bigtable_fixtures.py b/go/internal/feast/onlinestore/testdata/gen_bigtable_fixtures.py new file mode 100644 index 00000000000..eebe7563e15 --- /dev/null +++ b/go/internal/feast/onlinestore/testdata/gen_bigtable_fixtures.py @@ -0,0 +1,362 @@ +"""Generate Python-side parity fixtures for the Go Bigtable online store. + +Calls the in-tree Python BigtableOnlineStore: its table name and row key helpers, and its +writer (_write_rows_to_bt) through a table stand-in that records the cells. Prints +deterministic JSON on stdout; the Go tests in bigtableonlinestore_test.go read it from this +directory, and sdk/python/tests/unit/infra/online_store/test_bigtable_go_fixtures.py fails +when the committed file no longer matches what this SDK writes. + +Regenerate from the repository root: + + uv run --extra gcp python go/internal/feast/onlinestore/testdata/gen_bigtable_fixtures.py \ + > go/internal/feast/onlinestore/testdata/bigtable_fixtures.json + +Fixture schema: + table_names: [{project, entities, want}] + row_keys: [{name, entityless, join_keys, values: [{type, value}], view, want}] + want null = Go must reject; entityless = built from Feast's + DUMMY_ENTITY_ID/_VAL; value encoding: string and uuid as-is, bytes as + base64, int32 and int64 as decimal strings + cells: [{name, value_b64, event_ts, want_seconds, want_nanos, want_value}] + want_value = the ValueProto in proto3 JSON form with proto field + names, from typed_json (protojson-readable, and the same whether + or not Feast's proto_json.patch() has run) + murmur_vectors: [{length, want}] + want = mmh3.hash_bytes(bytes(range(length))).hex(), the entity-id hash + of Feast's compute_entity_id, for every length 1 to 100 (all 16-byte + tail sizes, several blocks) +""" + +import base64 +import json +import math +import struct +import sys +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from typing import Any, Dict, List, Tuple + +import mmh3 +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.message import Message + +from feast import utils +from feast.feature_view import DUMMY_ENTITY_ID, DUMMY_ENTITY_NAME, DUMMY_ENTITY_VAL +from feast.infra.online_stores.bigtable import BigtableOnlineStore +from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto +from feast.protos.feast.types.Value_pb2 import FloatList +from feast.protos.feast.types.Value_pb2 import Value as ValueProto +from feast.repo_config import RepoConfig + +SERIALIZATION_VERSION = 3 +SHORT_PROJECT = "my_project" +# 60 chars: longer than the room any entity part leaves, so the project is hashed. +LONG_PROJECT = "my_feature_store_project_with_a_deliberately_long_name_00060" + + +def repo_config(project: str) -> RepoConfig: + """Returns a Bigtable repo config for project.""" + return RepoConfig( + project=project, + registry="registry.db", + provider="gcp", + online_store={"type": "bigtable", "instance": "fixtures"}, + offline_store={"type": "file"}, + entity_key_serialization_version=SERIALIZATION_VERSION, + ) + + +def table_name_cases() -> List[Dict[str, Any]]: + """Returns Python's table name for each (project, entities) case.""" + cases = [ + (SHORT_PROJECT, ["subscriber"]), + (SHORT_PROJECT, ["title", "subscriber"]), + (SHORT_PROJECT, ["subscriber_profile_region"]), # 25 chars: hashed + # 10 chars, 30 UTF-8 bytes: kept, as the limit counts characters. + (SHORT_PROJECT, ["日本語日本語日本語日本"]), + # Project hash cut to 28 of the 32 md5 hex chars. + (LONG_PROJECT, ["subscriber"]), + # Short entity parts ask for 33 and 37 hash chars; Python clamps at 32. + (LONG_PROJECT, ["title"]), + (LONG_PROJECT, ["t"]), + (SHORT_PROJECT, []), # entityless, Python's else branch + # Entityless as FeatureView and the Go model store it. + (SHORT_PROJECT, [DUMMY_ENTITY_NAME]), + ] + assert len(LONG_PROJECT) == 60 + assert len("subscriber_profile_region") == 25 + out: List[Dict[str, Any]] = [] + for project, entities in cases: + fv = SimpleNamespace(name="fv", entities=entities) + want = BigtableOnlineStore._get_table_name( + config=repo_config(project), + feature_view=fv, # type: ignore[arg-type] + ) + out.append({"project": project, "entities": entities, "want": want}) + return out + + +def encode_value(type_name: str, value: Any) -> Dict[str, str]: + """Encodes an entity value as the fixture's {type, value}.""" + if type_name == "bytes": + return {"type": type_name, "value": base64.b64encode(value).decode()} + if type_name in ("int32", "int64"): + return {"type": type_name, "value": str(value)} + return {"type": type_name, "value": value} + + +def to_proto(type_name: str, value: Any) -> ValueProto: + """Returns value as a ValueProto of type_name.""" + field = { + "string": "string_val", + "bytes": "bytes_val", + "int32": "int32_val", + "int64": "int64_val", + "uuid": "uuid_val", + }[type_name] + return ValueProto(**{field: value}) + + +def row_key_cases() -> List[Dict[str, Any]]: + """Returns Python's row key per case; None marks a key Go must reject.""" + # (name, [(join_key, type, value)], view, go_must_reject) + cases: List[Tuple[str, List[Tuple[str, str, Any]], str, bool]] = [ + ("string", [("subscriber_id", "string", "abc")], "subscriber_features", False), + ( + "utf8 string", + [("subscriber_id", "string", "日本")], + "subscriber_features", + False, + ), + ("bytes", [("blob_id", "bytes", b"\x00\xff")], "blob_features", False), + ("int32", [("region_id", "int32", -7)], "region_features", False), + ("int64", [("title_id", "int64", -9007199254740993)], "title_features", False), + ( + "two join keys reversed", + [("title_id", "int64", 42), ("subscriber_id", "string", "abc")], + "subscriber_title_features", + False, + ), + ( + "entityless", + [(DUMMY_ENTITY_ID, "string", DUMMY_ENTITY_VAL)], + "global_stats", + False, + ), + ( + "uuid", + [("session_id", "uuid", "0b3e7c1a-6a2f-4c55-9f4e-1d2c3b4a5f60")], + "session_features", + True, + ), + ] + store = BigtableOnlineStore() + config = repo_config(SHORT_PROJECT) + out: List[Dict[str, Any]] = [] + for name, keys, view, go_must_reject in cases: + entity_key = EntityKeyProto( + join_keys=[k for k, _, _ in keys], + entity_values=[to_proto(t, v) for _, t, v in keys], + ) + # Python computes a key for every case, uuid included, so all are writable keys. + key = store._compute_row_key(entity_key, view, config).decode() + out.append( + { + "name": name, + "entityless": [k for k, _, _ in keys] == [DUMMY_ENTITY_ID], + "join_keys": [k for k, _, _ in keys], + "values": [encode_value(t, v) for _, t, v in keys], + "view": view, + "want": None if go_must_reject else key, + } + ) + return out + + +class _RecordingRow: + """Stands in for a Bigtable DirectRow and records the cells set on it.""" + + def __init__(self, key: bytes) -> None: + """Start an empty row with row key key.""" + self.key = key + self.cells: Dict[bytes, bytes] = {} + + def set_cell(self, family: str, qualifier: bytes, value: bytes) -> None: + """Record value under qualifier; every cell must be in the features family.""" + assert family == BigtableOnlineStore.feature_column_family + self.cells[qualifier] = value + + +class _RecordingTable: + """Stands in for a Bigtable table and records the rows _write_rows_to_bt builds.""" + + def __init__(self) -> None: + """Start with no rows.""" + self.rows: List[_RecordingRow] = [] + + def direct_row(self, key: bytes) -> _RecordingRow: + """Return a new recording row for key and keep it.""" + row = _RecordingRow(key) + self.rows.append(row) + return row + + def mutate_rows(self, rows: List[_RecordingRow]) -> None: + """Do nothing: the rows were already recorded by direct_row.""" + + +def written_cells(value: ValueProto, ts: datetime) -> Dict[bytes, bytes]: + """Returns the cells the Python writer sets for one row with feature "f".""" + table = _RecordingTable() + entity_key = EntityKeyProto( + join_keys=["subscriber_id"], entity_values=[ValueProto(string_val="abc")] + ) + BigtableOnlineStore()._write_rows_to_bt( + [(entity_key, {"f": value}, ts, None)], + table, # type: ignore[arg-type] + "fv", + repo_config(SHORT_PROJECT), + None, + ) + (row,) = table.rows + return row.cells + + +_INT64_TYPES = { + FieldDescriptor.TYPE_INT64, + FieldDescriptor.TYPE_UINT64, + FieldDescriptor.TYPE_SINT64, + FieldDescriptor.TYPE_FIXED64, + FieldDescriptor.TYPE_SFIXED64, +} + + +def _typed_scalar(field: FieldDescriptor, value: Any) -> Any: + """Returns one scalar field value in proto3 JSON form.""" + if field.type in _INT64_TYPES: + return str(value) + if field.type == FieldDescriptor.TYPE_BYTES: + return base64.b64encode(value).decode() + if field.type == FieldDescriptor.TYPE_ENUM: + # proto3 enums are open: a number with no name prints as the number. + known = field.enum_type.values_by_number.get(value) + return value if known is None else known.name + if field.type in (FieldDescriptor.TYPE_FLOAT, FieldDescriptor.TYPE_DOUBLE): + if math.isnan(value): + return "NaN" + if math.isinf(value): + return "Infinity" if value > 0 else "-Infinity" + if field.type == FieldDescriptor.TYPE_FLOAT: + # The shortest decimal that reads back as the same float32. + packed = struct.pack(" bool: + """Reports whether field is repeated; newer protobuf releases drop .label.""" + if hasattr(field, "is_repeated"): + return field.is_repeated + return field.label == FieldDescriptor.LABEL_REPEATED + + +def typed_json(message: Message) -> Dict[str, Any]: + """Returns message in proto3 JSON form with proto field names, built from its + descriptor alone. + + json_format.MessageToDict would print the same for a ValueProto, but Feast's + proto_json.patch() rewrites how MessageToDict prints ValueProto for the whole + process (a bare 1 instead of {"int64_val": "1"}), and whether a test in the same + process has applied it depends on test order. Go reads this form with + protojson.Unmarshal. + """ + out: Dict[str, Any] = {} + for field, value in message.ListFields(): + if field.message_type is not None and field.message_type.GetOptions().map_entry: + value_field = field.message_type.fields_by_name["value"] + out[field.name] = { + str(k): _typed_scalar(value_field, v) for k, v in value.items() + } + elif _is_repeated(field): + out[field.name] = [_typed_scalar(field, v) for v in value] + else: + out[field.name] = _typed_scalar(field, value) + return out + + +def cell_cases() -> List[Dict[str, Any]]: + """Returns the cells Python writes for each value and event timestamp case.""" + with_micros = datetime(2026, 11, 17, 10, 0, 0, 123456, tzinfo=timezone.utc) + whole_second = datetime(2026, 11, 17, 10, 0, 0, tzinfo=timezone.utc) + ist = datetime( + 2026, 11, 17, 15, 30, 0, 250000, tzinfo=timezone(timedelta(hours=5, minutes=30)) + ) + # make_tzaware turns this into UTC, as the writer does. + naive = datetime(2026, 11, 17, 10, 0, 0) + cases = [ + ("int64", ValueProto(int64_val=-9007199254740993), with_micros), + ("double", ValueProto(double_val=0.1), whole_second), + ("string", ValueProto(string_val="日本 abc"), ist), + ("bool", ValueProto(bool_val=True), naive), + ( + "float list", + ValueProto(float_list_val=FloatList(val=[0.5, -1.25, 3.0])), + with_micros, + ), + ("null", ValueProto(), whole_second), + ] + epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) + out: List[Dict[str, Any]] = [] + for name, value, ts in cases: + cells = written_cells(value, ts) + # The expected instant, computed independently of the writer's encoding. + aware = utils.make_tzaware(ts) + out.append( + { + "name": name, + "value_b64": base64.b64encode(cells[b"f"]).decode(), + "event_ts": cells[b"event_ts"].decode(), + "want_seconds": (aware - epoch) // timedelta(seconds=1), + "want_nanos": aware.microsecond * 1000, + "want_value": typed_json(value), + } + ) + return out + + +def murmur_vectors() -> List[Dict[str, Any]]: + """Returns Python's entity hash of bytes(range(n)) for n from 1 to 100.""" + # compute_entity_id (feast/infra/online_stores/helpers.py) is + # mmh3.hash_bytes(serialized key).hex(): x64 128-bit, seed 0, h1 then h2 + # little-endian. + return [ + {"length": n, "want": mmh3.hash_bytes(bytes(range(n))).hex()} + for n in range(1, 101) + ] + + +def build_fixtures() -> Dict[str, List[Dict[str, Any]]]: + """Returns every fixture, as written to bigtable_fixtures.json.""" + return { + "table_names": table_name_cases(), + "row_keys": row_key_cases(), + "cells": cell_cases(), + "murmur_vectors": murmur_vectors(), + } + + +def main() -> None: + """Prints the fixtures as JSON.""" + json.dump( + build_fixtures(), sys.stdout, indent=2, sort_keys=True, ensure_ascii=False + ) + sys.stdout.write("\n") + + +if __name__ == "__main__": + main() diff --git a/sdk/python/feast/infra/online_stores/bigtable.py b/sdk/python/feast/infra/online_stores/bigtable.py index ccc4af5e2e5..c6582881623 100644 --- a/sdk/python/feast/infra/online_stores/bigtable.py +++ b/sdk/python/feast/infra/online_stores/bigtable.py @@ -3,12 +3,30 @@ import re from concurrent import futures from datetime import datetime -from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple +from typing import ( + Annotated, + Any, + Callable, + Dict, + List, + Literal, + Optional, + Sequence, + Set, + Tuple, +) import google from google.cloud import bigtable from google.cloud.bigtable import row_filters -from pydantic import NonNegativeInt, PositiveInt, StrictStr +from pydantic import ( + Field, + NonNegativeInt, + PositiveInt, + StrictBool, + StrictInt, + StrictStr, +) from feast import Entity, FeatureView, utils from feast.feature_view import DUMMY_ENTITY_NAME @@ -42,6 +60,11 @@ # 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 +# The Go feature server reads its numeric settings as whole numbers up to MaxInt32 and +# rejects quoted numbers and booleans, so the Python config accepts the same values. +GO_MAX_INT = 2**31 - 1 +GoPositiveInt = Annotated[StrictInt, Field(gt=0, le=GO_MAX_INT)] +GoNonNegativeInt = Annotated[StrictInt, Field(ge=0, le=GO_MAX_INT)] class BigtableOnlineStoreConfig(FeastConfigBaseModel): @@ -74,6 +97,74 @@ class BigtableOnlineStoreConfig(FeastConfigBaseModel): are read with one ReadRows call per Bigtable table. Set to 0 to always read one feature view at a time. Defaults to 2048.""" + app_profile: Optional[StrictStr] = None + """(optional) Bigtable app profile for online reads, by the Go feature server and the + Python SDK. Python writes use ``write_app_profile`` instead. The profile must already + exist on the instance. When unset, the instance's default app profile is used.""" + + write_app_profile: Optional[StrictStr] = None + """(optional) Bigtable app profile for the Python SDK's writes (materialization and + push). When unset, the instance's default app profile is used; it does not fall back + to ``app_profile``, so setting ``app_profile`` alone never moves writes onto the + serving profile. Point it at a low-priority app profile so writes do not compete with + serving reads.""" + + initial_tablets: Optional[Annotated[int, Field(ge=2, le=256)]] = None + """(optional) When set, ``feast apply`` creates each new table pre-split into this many + tablets, at evenly spaced row key prefixes. Row keys start with a uniform hex hash, so + the tablets fill evenly, and a small table can be served by several nodes from the + start instead of one. As a rule of thumb, use a few tablets per node at the node count + you expect to run. Between 2 and 256. When unset, a new table starts as one tablet. + Existing tables are not changed.""" + + keys_per_request: Optional[Annotated[StrictInt, Field(gt=0, le=100)]] = None + """(optional) Used by the Go feature server. Number of row keys per Bigtable ReadRows + request; a read is split into chunks of this size. Higher values make fewer calls and + use less CPU, at the cost of latency. Between 1 and 100. Set it to 1, with + ``adaptive_chunking`` off, for reads to use Bigtable's in-memory tier, which serves + only single-row reads. Defaults to 5 in the Go feature server.""" + + max_concurrent_chunks: Optional[GoPositiveInt] = None + """(optional) Used by the Go feature server. Maximum number of chunks one online read + sends to Bigtable at the same time. Limits a single read call, not the whole server + (see ``max_inflight_reads``). Lower values reduce the load on a small instance at the + cost of latency for large reads. Defaults to 50 in the Go feature server.""" + + max_inflight_reads: Optional[GoPositiveInt] = None + """(optional) Used by the Go feature server. Maximum number of ReadRows calls in flight + across all online reads of the server. A read reserves all the slots it needs, up to + ``max_concurrent_chunks``, before it sends anything, and is rejected when they are not + free within ``max_inflight_wait_ms`` (RESOURCE_EXHAUSTED over gRPC, 500 over HTTP), so a + lower cap protects the instance under load at the cost of rejected reads. Keep it + several times ``max_concurrent_chunks``. When unset, there is no limit.""" + + max_inflight_wait_ms: Optional[GoNonNegativeInt] = None + """(optional) Used by the Go feature server. How long, in milliseconds, a read waits for + free ``max_inflight_reads`` slots before it is rejected. 0 rejects it at once; a short + wait, such as 10 to 20, absorbs bursts at the cost of that much latency for the reads + that wait. Applies only when ``max_inflight_reads`` is set. Defaults to 0 in the Go + feature server.""" + + read_timeout_ms: Optional[GoPositiveInt] = None + """(optional) Used by the Go feature server. Time budget in milliseconds for one online + read, including retries. The caller's deadline still applies, so the shorter one wins. + Lower values fail slow reads sooner. Defaults to 60000 (60 s) in the Go feature + server, a ceiling that stops the client retrying without end rather than a latency + target.""" + + adaptive_chunking: Optional[StrictBool] = None + """(optional) Used by the Go feature server. When true, ``keys_per_request`` is the + smallest chunk size: a read that would need more than ``max_concurrent_chunks`` chunks + gets larger chunks, up to 100 keys, so it fits in that many calls where it can. Large + reads make fewer calls, but each larger chunk is slower. Defaults to false in the Go + feature server.""" + + disable_metrics: Optional[StrictBool] = None + """(optional) Used by the Go feature server. When true, the Bigtable client exports no + client-side metrics to Cloud Monitoring, so the serving identity needs no + ``monitoring.timeSeries.create`` permission and the server uses less CPU, at the cost + of those metrics. Defaults to false in the Go feature server.""" + class BigtableOnlineStore(OnlineStore): _client: Optional[bigtable.Client] = None @@ -296,7 +387,9 @@ def _read_rows( ) -> 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) + bt_table = bt_instance.table( + bt_table_name, app_profile_id=config.online_store.app_profile + ) row_set = bigtable.row_set.RowSet() for row_key in row_keys: @@ -341,7 +434,10 @@ def online_write_batch( 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) + bt_table = bt_instance.table( + bt_table_name, + app_profile_id=config.online_store.write_app_profile, + ) # `columns_per_row` is used to calculate the number of rows we are allowed to # mutate in one request. @@ -441,6 +537,8 @@ def update( We use a dedicated table for each entity combination. For example, if a FeatureView uses the entities `shop` and `customer`, the resulting table would be called `customer-shop` (entities are sorted lexicographically first). + + New tables are pre-split when ``initial_tablets`` is set. """ online_config = config.online_store assert isinstance(online_config, BigtableOnlineStoreConfig) @@ -449,6 +547,7 @@ def update( max_versions_gc_rule = bigtable.column_family.MaxVersionsGCRule( online_config.max_versions ) + split_keys = self._initial_split_keys(online_config.initial_tablets) # The word "table" in the arguments refers to feature_views (this is for legacy # reasons). To reduce confusion with bigtable tables, we use alternate variable # names @@ -471,7 +570,10 @@ def update( bt_table = bt_instance.table(bt_table_name) if not bt_table.exists(): logger.info(f"Creating table `{bt_table_name}` in Bigtable") - bt_table.create() + if split_keys: + bt_table.create(initial_split_keys=split_keys) + else: + bt_table.create() else: logger.info(f"Table {bt_table_name} already exists in Bigtable") @@ -485,6 +587,17 @@ def update( logger.info(f"Deleting table {bt_table_name} in Bigtable") bt_table.delete() + @staticmethod + def _initial_split_keys(tablets: Optional[int]) -> List[bytes]: + """Returns the split keys that cut a table into ``tablets`` tablets. + + Row keys start with the lowercase hex of a uniform hash, so two-hex-digit split + points at even steps over 00..ff give tablets of about the same size. + """ + if not tablets: + return [] + return [f"{i * 256 // tablets:02x}".encode() for i in range(1, tablets)] + @staticmethod def _get_table_name(config: RepoConfig, feature_view: FeatureView) -> str: entities_part = ( 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 index acf19095d04..c9ad601134a 100644 --- 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 @@ -2,7 +2,7 @@ import re from datetime import timedelta -from typing import Dict, List, Tuple +from typing import Dict, List, Optional, Tuple from unittest.mock import patch import pytest @@ -102,12 +102,15 @@ def __init__(self): self.calls: List[Tuple[str, List[bytes]]] = [] # (row key, column) of every feature cell returned, event_ts aside. self.cells: List[Tuple[bytes, bytes]] = [] + # The app profile of every table opened. + self.app_profiles: List[Optional[str]] = [] def instance(self, instance_id): return self - def table(self, table_name): + def table(self, table_name, app_profile_id=None): fake = self + fake.app_profiles.append(app_profile_id) class _Table: def read_rows(self, row_set, filter_=None): @@ -226,6 +229,18 @@ def test_views_on_same_entities_share_one_read_rows_call(setup): } +def test_batched_read_uses_the_read_app_profile(): + store, fake = BigtableOnlineStore(), _FakeBigtable() + config = _config(app_profile="serve", write_app_profile="batch") + views = [_feature_view(f"fv{i}", [f"f{i}"]) for i in range(2)] + grouped_refs = [(fv, [f"f{i}"]) for i, fv in enumerate(views)] + + _, calls = _read(store, config, fake, grouped_refs, _drivers(1)) + + assert len(calls) == 1 + assert fake.app_profiles == ["serve"] + + def test_views_on_different_entities_read_once_per_table(setup): store, config, fake = setup by_driver = _feature_view("by_driver", ["trips"]) diff --git a/sdk/python/tests/unit/infra/online_store/test_bigtable_go_fixtures.py b/sdk/python/tests/unit/infra/online_store/test_bigtable_go_fixtures.py new file mode 100644 index 00000000000..0f5c3531b7b --- /dev/null +++ b/sdk/python/tests/unit/infra/online_store/test_bigtable_go_fixtures.py @@ -0,0 +1,190 @@ +"""The Go Bigtable online store's parity fixtures must match what this SDK writes.""" + +import importlib.util +import json +import pathlib +from types import ModuleType +from typing import Any, Dict, Iterator + +import pytest +from google.protobuf import json_format + +from feast import proto_json +from feast.protos.feast.serving.ServingService_pb2 import FeatureList +from feast.protos.feast.types.Value_pb2 import ( + BoolSet, + BytesList, + DoubleList, + FloatList, + Int32Set, + Int64Set, + Map, + MapKey, + MapList, + Null, + RepeatedValue, + ScalarMap, + ScalarMapEntry, + StringList, + ZonedTimestamp, +) +from feast.protos.feast.types.Value_pb2 import Value as ValueProto + +pytest.importorskip("google.cloud.bigtable") + +TESTDATA = ( + pathlib.Path(__file__).resolve().parents[6] + / "go" + / "internal" + / "feast" + / "onlinestore" + / "testdata" +) + +# The message types whose JSON form proto_json.patch() replaces. +_PATCHED_TYPES = [ + m.DESCRIPTOR.full_name for m in (ValueProto, RepeatedValue, FeatureList) +] + + +@pytest.fixture +def generator() -> ModuleType: + """Loads testdata/gen_bigtable_fixtures.py as a module.""" + if not TESTDATA.is_dir(): + pytest.skip("the Go sources are not in this checkout") + spec = importlib.util.spec_from_file_location( + "gen_bigtable_fixtures", TESTDATA / "gen_bigtable_fixtures.py" + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def committed() -> Dict[str, Any]: + """Returns the committed bigtable_fixtures.json.""" + return json.loads((TESTDATA / "bigtable_fixtures.json").read_text(encoding="utf-8")) + + +@pytest.fixture +def json_methods() -> Iterator[Dict[str, Any]]: + """Yields json_format's per-type JSON methods and restores them afterwards. + + proto_json.patch() registers Feast's JSON form in this table for the whole process, + so each test sets the state it needs here instead of depending on test order. + """ + methods = json_format._WKTJSONMETHODS + saved = dict(methods) + yield methods + methods.clear() + methods.update(saved) + + +def _assert_matches(generator: ModuleType, committed: Dict[str, Any]) -> None: + assert generator.build_fixtures() == committed, ( + "The Go Bigtable fixtures no longer match the Python writer. Regenerate them " + "with the command in testdata/gen_bigtable_fixtures.py and check the Go tests." + ) + + +def test_go_fixtures_match_python_writer_without_json_patch( + generator: ModuleType, committed: Dict[str, Any], json_methods: Dict[str, Any] +) -> None: + """Fail when the committed fixtures drift from the in-tree Python store.""" + for name in _PATCHED_TYPES: + json_methods.pop(name, None) + assert json_format.MessageToDict( + ValueProto(int64_val=-9007199254740993), preserving_proto_field_name=True + ) == {"int64_val": "-9007199254740993"} + _assert_matches(generator, committed) + + +def test_go_fixtures_match_python_writer_with_json_patch( + generator: ModuleType, committed: Dict[str, Any], json_methods: Dict[str, Any] +) -> None: + """The fixtures stay the same after Feast patches protobuf's JSON printer.""" + proto_json.patch() + # The patch is in effect: MessageToDict now prints a bare value. + assert ( + json_format.MessageToDict(ValueProto(int64_val=-9007199254740993)) + == -9007199254740993 + ) + _assert_matches(generator, committed) + + +def _unknown_null() -> ValueProto: + """Returns a Value whose null_val holds a number Null has no name for.""" + value = ValueProto() + value.null_val = 7 # type: ignore[assignment] + return value + + +# One Value per JSON shape: every scalar kind, list and set wrappers, the Null enum, +# maps, nested Values and nested messages. +_VALUES = [ + ValueProto(), + ValueProto(bytes_val=b"\x00\xff"), + ValueProto(string_val="日本 abc"), + ValueProto(int32_val=-7), + ValueProto(int64_val=0), + ValueProto(int64_val=-9007199254740993), + ValueProto(double_val=0.1), + ValueProto(double_val=float("nan")), + ValueProto(double_val=float("-inf")), + ValueProto(float_val=0.1), + ValueProto(float_val=float("inf")), + ValueProto(bool_val=False), + ValueProto(unix_timestamp_val=1763373600), + ValueProto(bytes_list_val=BytesList(val=[b"a", b""])), + ValueProto(string_list_val=StringList(val=[])), + ValueProto(double_list_val=DoubleList(val=[0.1, -2.5])), + ValueProto(float_list_val=FloatList(val=[0.1, -1.25, 3.0])), + ValueProto(int64_set_val=Int64Set(val=[1, -9007199254740993])), + ValueProto(int32_set_val=Int32Set(val=[-7, 0])), + ValueProto(bool_set_val=BoolSet(val=[True, False])), + ValueProto(json_val='{"a": 1}'), + ValueProto(decimal_val="1.50"), + ValueProto(uuid_list_val=StringList(val=["0b3e7c1a-6a2f-4c55-9f4e-1d2c3b4a5f60"])), + ValueProto(null_val=Null.NULL), + _unknown_null(), + ValueProto( + map_val=Map(val={"a": ValueProto(int64_val=5), "b": ValueProto(string_val="x")}) + ), + ValueProto( + list_val=RepeatedValue( + val=[ValueProto(int64_val=1), ValueProto(), ValueProto(bool_val=True)] + ) + ), + ValueProto( + map_list_val=MapList( + val=[Map(val={"a": ValueProto(double_val=0.5)}), Map(val={})] + ) + ), + ValueProto( + set_val=RepeatedValue( + val=[ValueProto(string_val="a"), ValueProto(int64_val=-1)] + ) + ), + ValueProto( + scalar_map_val=ScalarMap( + val=[ + ScalarMapEntry(key=MapKey(int64_key=2), value=ValueProto(float_val=0.5)) + ] + ) + ), + ValueProto( + zoned_timestamp_val=ZonedTimestamp(unix_timestamp=1, zone="Asia/Kolkata") + ), +] + + +@pytest.mark.parametrize("value", _VALUES, ids=lambda v: v.WhichOneof("val") or "unset") +def test_typed_json_matches_unpatched_message_to_dict( + generator: ModuleType, json_methods: Dict[str, Any], value: ValueProto +) -> None: + """typed_json prints what protobuf itself prints for a Value before the patch.""" + for name in _PATCHED_TYPES: + json_methods.pop(name, None) + want = json_format.MessageToDict(value, preserving_proto_field_name=True) + assert generator.typed_json(value) == want diff --git a/sdk/python/tests/unit/infra/online_store/test_bigtable_online_store.py b/sdk/python/tests/unit/infra/online_store/test_bigtable_online_store.py index a9db16aec10..ca6448276be 100644 --- a/sdk/python/tests/unit/infra/online_store/test_bigtable_online_store.py +++ b/sdk/python/tests/unit/infra/online_store/test_bigtable_online_store.py @@ -1,7 +1,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone -from typing import List -from unittest.mock import patch +from typing import Dict, List, Optional +from unittest.mock import MagicMock, patch import pytest @@ -9,12 +9,20 @@ from concurrent import futures # noqa: E402 +from google.cloud.bigtable.column_family import ( # noqa: E402 + GarbageCollectionRule, + MaxVersionsGCRule, +) + import feast.infra.online_stores.bigtable as bigtable_module # noqa: E402 from feast.infra.offline_stores.dask import DaskOfflineStoreConfig # noqa: E402 from feast.infra.online_stores.bigtable import ( # noqa: E402 BigtableOnlineStore, BigtableOnlineStoreConfig, ) +from feast.protos.feast.types.EntityKey_pb2 import ( # noqa: E402 + EntityKey as EntityKeyProto, +) from feast.repo_config import RepoConfig # noqa: E402 @@ -67,7 +75,17 @@ def test_defaults_match_legacy_constants(): ) -@pytest.mark.parametrize("field_name", ["mutations_per_write", "write_concurrency"]) +@pytest.mark.parametrize( + "field_name", + [ + "mutations_per_write", + "write_concurrency", + "keys_per_request", + "max_concurrent_chunks", + "read_timeout_ms", + "max_inflight_reads", + ], +) @pytest.mark.parametrize("bad_value", [0, -1]) def test_positive_int_validation(field_name, bad_value): from pydantic import ValidationError @@ -76,6 +94,87 @@ def test_positive_int_validation(field_name, bad_value): BigtableOnlineStoreConfig(instance="test-instance", **{field_name: bad_value}) +@pytest.mark.parametrize("bad_value", [-1, 2.5]) +def test_max_inflight_wait_ms_validation(bad_value: object) -> None: + """Accept a max_inflight_wait_ms of 0 and reject negative and fractional values.""" + from pydantic import ValidationError + + assert ( + BigtableOnlineStoreConfig( + instance="test-instance", max_inflight_wait_ms=0 + ).max_inflight_wait_ms + == 0 + ) + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig( + instance="test-instance", + max_inflight_wait_ms=bad_value, # type: ignore[arg-type] + ) + + +def test_keys_per_request_upper_bound() -> None: + """Accept keys_per_request of 100 and reject 101.""" + from pydantic import ValidationError + + assert ( + BigtableOnlineStoreConfig( + instance="test-instance", keys_per_request=100 + ).keys_per_request + == 100 + ) + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig(instance="test-instance", keys_per_request=101) + + +@pytest.mark.parametrize( + "field_name", + [ + "keys_per_request", + "max_concurrent_chunks", + "read_timeout_ms", + "max_inflight_reads", + "max_inflight_wait_ms", + "adaptive_chunking", + "disable_metrics", + "initial_tablets", + "write_app_profile", + ], +) +def test_go_reader_fields_accept_null(field_name: str) -> None: + """Treat a null Go reader field as unset, so the Go feature server's default applies.""" + config = BigtableOnlineStoreConfig( + instance="test-instance", + **{field_name: None}, # type: ignore[arg-type] + ) + assert getattr(config, field_name) is None + + # A bare `key:` in feature_store.yaml reaches the config as None in a dict. + yaml_config = RepoConfig( + registry="s3://test_registry/registry.db", + project="test_bigtable", + provider="local", + online_store={"type": "bigtable", "instance": "i", field_name: None}, + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + assert getattr(yaml_config.online_store, field_name) is None + + +def test_max_versions_alongside_go_reader_fields() -> None: + """Keep max_versions when the Go reader fields are set beside it.""" + config = BigtableOnlineStoreConfig( + instance="test-instance", + max_versions=1, + app_profile="serve", + keys_per_request=25, + max_concurrent_chunks=8, + read_timeout_ms=150, + max_inflight_reads=300, + ) + assert config.max_versions == 1 + assert config.keys_per_request == 25 + + def test_online_write_batch_respects_mutations_per_write(): # 1 feature -> columns_per_row = 2 -> rows_per_write = max(1, 10 // 2) = 5 store = BigtableOnlineStore() @@ -117,3 +216,316 @@ def test_write_concurrency_sets_thread_pool_size(): store.online_write_batch(config, feature_view, _rows(4), None) mock_pool.assert_called_once_with(max_workers=3) + + +def test_bigtable_config_accepts_go_reader_fields() -> None: + """Accept the Go reader fields from kwargs and from a YAML-style dict.""" + from pydantic import ValidationError + + config = _make_repo_config( + app_profile="serve", + keys_per_request=25, + max_concurrent_chunks=8, + read_timeout_ms=150, + max_inflight_reads=300, + max_inflight_wait_ms=15, + adaptive_chunking=True, + disable_metrics=True, + ) + online_store = config.online_store + assert online_store.instance == "test-instance" + assert online_store.app_profile == "serve" + assert online_store.keys_per_request == 25 + assert online_store.max_concurrent_chunks == 8 + assert online_store.read_timeout_ms == 150 + assert online_store.max_inflight_reads == 300 + assert online_store.max_inflight_wait_ms == 15 + assert online_store.adaptive_chunking is True + assert online_store.disable_metrics is True + + with pytest.raises(ValidationError): + _make_repo_config(keys_per_request=101) + + # feature_store.yaml reaches the config as a dict, so check that path as well. + yaml_config = RepoConfig( + registry="s3://test_registry/registry.db", + project="test_bigtable", + provider="local", + online_store={ + "type": "bigtable", + "instance": "i", + "app_profile": "serve", + "keys_per_request": 25, + "max_concurrent_chunks": 8, + "read_timeout_ms": 150, + "max_inflight_reads": 300, + "max_inflight_wait_ms": 0, + "adaptive_chunking": True, + "disable_metrics": False, + }, + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + assert isinstance(yaml_config.online_store, BigtableOnlineStoreConfig) + assert yaml_config.online_store.keys_per_request == 25 + assert yaml_config.online_store.adaptive_chunking is True + assert yaml_config.online_store.max_inflight_reads == 300 + assert yaml_config.online_store.max_inflight_wait_ms == 0 + assert yaml_config.online_store.disable_metrics is False + + defaults = BigtableOnlineStoreConfig(instance="test-instance") + assert defaults.app_profile is None + assert defaults.keys_per_request is None + assert defaults.max_concurrent_chunks is None + assert defaults.read_timeout_ms is None + assert defaults.max_inflight_reads is None + assert defaults.max_inflight_wait_ms is None + assert defaults.adaptive_chunking is None + assert defaults.disable_metrics is None + + +@pytest.mark.parametrize("field_name", ["adaptive_chunking", "disable_metrics"]) +@pytest.mark.parametrize("bad_value", ["true", 1]) +def test_go_reader_switches_reject_non_bool(field_name: str, bad_value: object) -> None: + """Reject a quoted or numeric switch, as the Go feature server does.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig( + instance="test-instance", + **{field_name: bad_value}, # type: ignore[arg-type] + ) + + +@pytest.mark.parametrize( + "field_name", + [ + "keys_per_request", + "max_concurrent_chunks", + "max_inflight_reads", + "max_inflight_wait_ms", + "read_timeout_ms", + ], +) +@pytest.mark.parametrize("bad_value", ["5", True, 2**31]) +def test_go_reader_numbers_reject_what_go_rejects( + field_name: str, bad_value: object +) -> None: + """Reject a quoted, boolean or above-MaxInt32 number, as the Go feature server does.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig( + instance="test-instance", + **{field_name: bad_value}, # type: ignore[arg-type] + ) + + +def test_go_reader_numbers_accept_max_int32() -> None: + """Accept MaxInt32, the largest value the Go feature server reads.""" + config = BigtableOnlineStoreConfig( + instance="test-instance", read_timeout_ms=2**31 - 1, max_inflight_wait_ms=0 + ) + + assert config.read_timeout_ms == 2**31 - 1 + assert config.max_inflight_wait_ms == 0 + + +@dataclass +class _View: + """A feature view stand-in with what update() and _get_table_name read.""" + + name: str + entities: List[str] + + +class _FakeTable: + """A Bigtable table handle that records create and column family create.""" + + def __init__( + self, exists: bool, gc_rule: Optional[GarbageCollectionRule] = None + ) -> None: + self._exists = exists + self.families: Dict[str, MagicMock] = ( + {} if gc_rule is None else {"features": MagicMock(gc_rule=gc_rule)} + ) + self.create = MagicMock() + self.created_rules: List[Optional[GarbageCollectionRule]] = [] + + def exists(self) -> bool: + """Report whether the table exists.""" + return self._exists + + def list_column_families(self) -> Dict[str, MagicMock]: + """Return the table's column families by name.""" + return self.families + + def column_family( + self, name: str, gc_rule: Optional[GarbageCollectionRule] = None + ) -> MagicMock: + """Return a family handle whose create() records gc_rule.""" + family = MagicMock() + family.create.side_effect = lambda: self.created_rules.append(gc_rule) + return family + + +def _run_update(config: RepoConfig, views: List[_View], table: _FakeTable) -> None: + """Run BigtableOnlineStore.update() for views against a client that returns table.""" + client = MagicMock() + client.instance.return_value.table.return_value = table + with patch.object(BigtableOnlineStore, "_get_client", return_value=client): + BigtableOnlineStore().update( + config, + tables_to_delete=[], + tables_to_keep=views, # type: ignore[arg-type] + entities_to_delete=[], + entities_to_keep=[], + partial=False, + ) + + +def _versions(n: int = 2) -> MaxVersionsGCRule: + """Return the max-versions rule update() creates for max_versions n.""" + return MaxVersionsGCRule(n) + + +def test_initial_split_keys() -> None: + """Split a table into evenly spaced two-hex-digit prefixes.""" + split = BigtableOnlineStore._initial_split_keys + assert split(None) == [] + assert split(2) == [b"80"] + assert split(4) == [b"40", b"80", b"c0"] + assert split(16) == [f"{i:x}0".encode() for i in range(1, 16)] + keys = split(256) + assert len(keys) == 255 + assert keys == sorted(set(keys)) + assert keys[0] == b"01" and keys[-1] == b"ff" + + +@pytest.mark.parametrize("bad_value", [0, 1, 257]) +def test_initial_tablets_bounds(bad_value: int) -> None: + """Reject initial_tablets outside 2 to 256.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError): + BigtableOnlineStoreConfig(instance="test-instance", initial_tablets=bad_value) + + +def test_update_creates_unsplit_table_by_default() -> None: + """Keep today's behavior: no split keys and a max-versions rule.""" + table = _FakeTable(exists=False) + _run_update(_make_repo_config(), [_View("fv", ["user"])], table) + table.create.assert_called_once_with() + assert table.created_rules == [_versions()] + + +def test_update_presplits_new_tables() -> None: + """Pass the split keys to create() for a new table.""" + table = _FakeTable(exists=False) + _run_update(_make_repo_config(initial_tablets=4), [_View("fv", ["user"])], table) + table.create.assert_called_once_with(initial_split_keys=[b"40", b"80", b"c0"]) + assert table.created_rules == [_versions()] + + +def test_update_leaves_existing_table_unsplit() -> None: + """Never re-create or split a table that already exists.""" + table = _FakeTable(exists=True, gc_rule=_versions()) + _run_update(_make_repo_config(initial_tablets=4), [_View("fv", ["user"])], table) + table.create.assert_not_called() + assert table.created_rules == [] + + +def test_initial_tablets_from_yaml() -> None: + """Accept initial_tablets from a YAML-style dict; unset by default.""" + yaml_config = RepoConfig( + registry="s3://test_registry/registry.db", + project="test_bigtable", + provider="local", + online_store={"type": "bigtable", "instance": "i", "initial_tablets": 16}, + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + assert yaml_config.online_store.initial_tablets == 16 + assert BigtableOnlineStoreConfig(instance="i").initial_tablets is None + + +@pytest.mark.parametrize( + "online_store_kwargs, want_profile", + [ + ({}, None), + # app_profile alone never moves writes off the instance default. + ({"app_profile": "serve"}, None), + ({"app_profile": "serve", "write_app_profile": "batch"}, "batch"), + ({"write_app_profile": "batch"}, "batch"), + ], +) +def test_writes_use_write_app_profile( + online_store_kwargs: Dict[str, str], want_profile: Optional[str] +) -> None: + """Write through write_app_profile only, else the instance default.""" + config = _make_repo_config(**online_store_kwargs) + client = MagicMock() + with ( + patch.object(BigtableOnlineStore, "_get_client", return_value=client), + patch.object(BigtableOnlineStore, "_get_table_name", return_value="tbl"), + patch.object(BigtableOnlineStore, "_write_rows_to_bt"), + ): + BigtableOnlineStore().online_write_batch( + config, + MockFeatureView(name="fv", features=[object()]), # type: ignore[arg-type] + _rows(1), + None, + ) + client.instance.return_value.table.assert_called_once_with( + "tbl", app_profile_id=want_profile + ) + + +@pytest.mark.parametrize( + "online_store_kwargs, want_profile", + [ + ({}, None), + ({"app_profile": "serve", "write_app_profile": "batch"}, "serve"), + ], +) +def test_reads_use_app_profile( + online_store_kwargs: Dict[str, str], want_profile: Optional[str] +) -> None: + """Read through app_profile, never write_app_profile.""" + config = _make_repo_config(**online_store_kwargs) + client = MagicMock() + client.instance.return_value.table.return_value.read_rows.return_value = [] + with ( + patch.object(BigtableOnlineStore, "_get_client", return_value=client), + patch.object(BigtableOnlineStore, "_get_table_name", return_value="tbl"), + patch.object(BigtableOnlineStore, "_compute_row_key", return_value=b"k#fv"), + ): + got = BigtableOnlineStore().online_read( + config, + MockFeatureView(name="fv"), # type: ignore[arg-type] + [EntityKeyProto()], + ["f"], + ) + assert got == [(None, None)] + client.instance.return_value.table.assert_called_once_with( + "tbl", app_profile_id=want_profile + ) + + +def test_write_settings_from_yaml() -> None: + """Accept write_app_profile from a YAML-style dict; unset by default.""" + yaml_config = RepoConfig( + registry="s3://test_registry/registry.db", + project="test_bigtable", + provider="local", + online_store={ + "type": "bigtable", + "instance": "i", + "write_app_profile": "batch", + }, + offline_store=DaskOfflineStoreConfig(), + entity_key_serialization_version=3, + ) + assert yaml_config.online_store.write_app_profile == "batch" + defaults = BigtableOnlineStoreConfig(instance="i") + assert defaults.write_app_profile is None diff --git a/skills/feast-architecture/SKILL.md b/skills/feast-architecture/SKILL.md index 5a6049d237b..852f3aee885 100644 --- a/skills/feast-architecture/SKILL.md +++ b/skills/feast-architecture/SKILL.md @@ -252,6 +252,14 @@ Key packages: The Go server reads the registry directly (proto file or remote) and calls the online store. It does not support `feast apply` or materialization — those remain Python-only. +Online stores (`go/internal/feast/onlinestore/`): +- Every store implements `onlinestore.OnlineStore`; `NewOnlineStore` picks one by `online_store.type`: + `sqlite` (default), `redis`, `dynamodb`, `postgres` or `bigtable`. +- A store that needs entity names to locate data (Bigtable names its tables by entity set) also + implements `onlinestore.EntityAwareOnlineStore`. `FeatureStore.readFromOnlineStore` then calls + `OnlineReadWithEntities` with each view's entity names, taken from the same view snapshot the + request used to group its feature refs. + --- ## Feast Operator (Kubernetes)