Repository navigation
fix: Use UTC in SQLite online store timestamp adapters #7235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PandaAB
wants to merge
2
commits into
feast-dev:master
Choose a base branch
from
PandaAB:fix/sqlite-utc-timestamp-adapter
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
311 changes: 311 additions & 0 deletions
311
sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,311 @@ | ||
| """Regression tests for the SQLite online store's UTC timestamp handling. | ||
|
|
||
| Feast treats naive datetimes as UTC (see ``to_naive_utc`` and | ||
| ``make_tzaware``), so the SQLite datetime <-> epoch adapters must round-trip | ||
| UTC regardless of the process timezone. These tests flip the process TZ | ||
| between the write and read sides to cover hosts in different timezones. | ||
| """ | ||
|
|
||
| import os | ||
| import sqlite3 | ||
| import time | ||
| from datetime import datetime, timedelta, timezone | ||
|
|
||
| import pandas as pd | ||
| import pytest | ||
|
|
||
| from feast import ( | ||
| Entity, | ||
| FeatureStore, | ||
| FeatureView, | ||
| Field, | ||
| FileSource, | ||
| RepoConfig, | ||
| ) | ||
| from feast.infra.online_stores.helpers import compute_table_id | ||
| from feast.infra.online_stores.sqlite import ( | ||
| SqliteOnlineStore, | ||
| SqliteOnlineStoreConfig, | ||
| adapt_datetime_epoch, | ||
| convert_timestamp, | ||
| ) | ||
| from feast.protos.feast.serving.ServingService_pb2 import ( | ||
| FieldStatus, | ||
| GetOnlineFeaturesResponse, | ||
| ) | ||
| from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto | ||
| from feast.protos.feast.types.Value_pb2 import Value as ValueProto | ||
| from feast.types import Int64 | ||
| from feast.utils import _populate_response_from_feature_data, to_naive_utc | ||
| from feast.value_type import ValueType | ||
|
|
||
| TRIPS_VALUE = 7 | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def clean_tz_env(): | ||
| """Restore the process TZ to whatever the test found, set or unset.""" | ||
| original: str | None = os.environ.get("TZ") | ||
| try: | ||
| yield | ||
| finally: | ||
| if original is None: | ||
| os.environ.pop("TZ", None) | ||
| else: | ||
| os.environ["TZ"] = original | ||
| time.tzset() | ||
|
|
||
|
|
||
| def _entity_key(driver_id: int) -> EntityKeyProto: | ||
| return EntityKeyProto( | ||
| join_keys=["driver_id"], entity_values=[ValueProto(int64_val=driver_id)] | ||
| ) | ||
|
|
||
|
|
||
| def _set_process_tz(name: str) -> None: | ||
| os.environ["TZ"] = name | ||
| time.tzset() | ||
|
|
||
|
|
||
| def _stored_epochs(config: RepoConfig, view: FeatureView): | ||
| """Read the raw on-disk event_ts/created_ts values without converters.""" | ||
| conn = sqlite3.connect(config.online_store.path) | ||
| try: | ||
| return conn.execute( | ||
| f"SELECT event_ts, created_ts FROM " | ||
| f"{compute_table_id(config.project, view, config.registry.enable_online_feature_view_versioning)}" | ||
| ).fetchone() | ||
| finally: | ||
| conn.close() | ||
|
|
||
|
|
||
| def _raw_row_for_event_epoch(config: RepoConfig, view: FeatureView, event_epoch: int): | ||
| """Fetch the raw on-disk row whose event_ts integer equals event_epoch.""" | ||
| conn = sqlite3.connect(config.online_store.path) | ||
| try: | ||
| return conn.execute( | ||
| f"SELECT event_ts, created_ts FROM " | ||
| f"{compute_table_id(config.project, view, config.registry.enable_online_feature_view_versioning)} " | ||
| f"WHERE event_ts = ?", | ||
| (event_epoch,), | ||
| ).fetchone() | ||
| finally: | ||
| conn.close() | ||
|
|
||
|
|
||
| def _ttl_status(read_ts: datetime, view: FeatureView) -> FieldStatus.ValueType: | ||
| """Run the production TTL check on one online_read row and return its status.""" | ||
| response = GetOnlineFeaturesResponse() | ||
| _populate_response_from_feature_data( | ||
| requested_features=["trips"], | ||
| read_rows=[(read_ts, {"trips": ValueProto(int64_val=TRIPS_VALUE)})], | ||
| indexes=([0],), | ||
| online_features_response=response, | ||
| full_feature_names=False, | ||
| table=view, | ||
| output_len=1, | ||
| ) | ||
| return response.results[0].statuses[0] | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not hasattr(time, "tzset"), reason="time.tzset() is Unix-only") | ||
| @pytest.mark.parametrize( | ||
| ("write_tz", "read_tz"), | ||
| [ | ||
| ("UTC", "UTC"), | ||
| ("Asia/Shanghai", "UTC"), | ||
| ("UTC", "Asia/Shanghai"), | ||
| ("America/New_York", "UTC"), | ||
| ], | ||
| ) | ||
| def test_sqlite_online_store_utc_epochs_across_timezones( | ||
| tmp_path, clean_tz_env, write_tz, read_tz | ||
| ): | ||
| config = RepoConfig( | ||
| project="tz_probe", | ||
| registry=str(tmp_path / "registry.db"), | ||
| provider="local", | ||
| online_store=SqliteOnlineStoreConfig(path=str(tmp_path / "online.db")), | ||
| offline_store={"type": "dask"}, | ||
| entity_key_serialization_version=3, | ||
| ) | ||
| driver = Entity( | ||
| name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 | ||
| ) | ||
| view = FeatureView( | ||
| name="driver_stats", | ||
| entities=[driver], | ||
| ttl=timedelta(hours=1), | ||
| schema=[Field(name="trips", dtype=Int64)], | ||
| source=FileSource(path=str(tmp_path / "unused.parquet"), timestamp_field="ts"), | ||
| ) | ||
| # Whole seconds: the store persists timestamps as integer epochs. | ||
| event_ts = (datetime.now(tz=timezone.utc) - timedelta(minutes=5)).replace( | ||
| microsecond=0 | ||
| ) | ||
| created_ts = event_ts + timedelta(seconds=30) | ||
| event_epoch = int(event_ts.timestamp()) | ||
| created_epoch = int(created_ts.timestamp()) | ||
|
|
||
| _set_process_tz(write_tz) | ||
| store = SqliteOnlineStore() | ||
| store.update(config, [], [view], [], [driver], partial=False) | ||
| store.online_write_batch( | ||
| config, | ||
| view, | ||
| [ | ||
| ( | ||
| _entity_key(1), | ||
| {"trips": ValueProto(int64_val=TRIPS_VALUE)}, | ||
| event_ts, | ||
| created_ts, | ||
| ) | ||
| ], | ||
| None, | ||
| ) | ||
|
|
||
| stored_event_epoch, stored_created_epoch = _stored_epochs(config, view) | ||
| assert stored_event_epoch == event_epoch | ||
| assert stored_created_epoch == created_epoch | ||
|
|
||
| # Serve the same database from a process running in another timezone. | ||
| _set_process_tz(read_tz) | ||
| read_ts, features = SqliteOnlineStore().online_read(config, view, [_entity_key(1)])[ | ||
| 0 | ||
| ] | ||
| assert features["trips"].int64_val == TRIPS_VALUE | ||
| assert read_ts == event_ts | ||
| assert _ttl_status(read_ts, view) == FieldStatus.PRESENT | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not hasattr(time, "tzset"), reason="time.tzset() is Unix-only") | ||
| def test_legacy_local_time_rows_recovered_by_materialize(tmp_path, clean_tz_env): | ||
| """Rows written by the old local-time adapter stay shifted until a full | ||
| materialize rewrites them, and incremental materialization must not touch | ||
| rows that fall before its already-completed interval.""" | ||
| _set_process_tz("Asia/Shanghai") | ||
|
|
||
| config = RepoConfig( | ||
| project="tz_probe", | ||
| registry=str(tmp_path / "registry.db"), | ||
| provider="local", | ||
| online_store=SqliteOnlineStoreConfig(path=str(tmp_path / "online.db")), | ||
| offline_store={"type": "dask"}, | ||
| entity_key_serialization_version=3, | ||
| ) | ||
| driver = Entity( | ||
| name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 | ||
| ) | ||
| view = FeatureView( | ||
| name="driver_stats", | ||
| entities=[driver], | ||
| ttl=timedelta(hours=1), | ||
| schema=[Field(name="trips", dtype=Int64)], | ||
| source=FileSource( | ||
| path=str(tmp_path / "events.parquet"), timestamp_field="event_timestamp" | ||
| ), | ||
| ) | ||
| # Whole seconds: the store persists timestamps as integer epochs. The two | ||
| # driver 2 rows give the bookkeeping and incremental windows real data. | ||
| event_ts = (datetime.now(tz=timezone.utc) - timedelta(minutes=5)).replace( | ||
| microsecond=0 | ||
| ) | ||
| first_bookkeeping_ts = event_ts + timedelta(hours=2, minutes=30) | ||
| second_bookkeeping_ts = event_ts + timedelta(hours=4, minutes=30) | ||
| events = pd.DataFrame( | ||
| { | ||
| "driver_id": [1, 2, 2], | ||
| "trips": [10, 20, 21], | ||
| "event_timestamp": [event_ts, first_bookkeeping_ts, second_bookkeeping_ts], | ||
| } | ||
| ) | ||
| events.to_parquet(tmp_path / "events.parquet", index=False) | ||
|
|
||
| store = FeatureStore(config=config) | ||
| store.apply([driver, view]) | ||
|
|
||
| # Seed driver 1 with the store writer, then stamp the epoch the way the old | ||
| # adapter did: int(to_naive_utc(event_ts).timestamp()) resolved the naive | ||
| # UTC wall clock in the process local timezone, which is Asia/Shanghai here. | ||
| created_ts = event_ts + timedelta(seconds=30) | ||
| legacy_event_epoch = int(to_naive_utc(event_ts).timestamp()) | ||
| legacy_created_epoch = int(to_naive_utc(created_ts).timestamp()) | ||
| SqliteOnlineStore().online_write_batch( | ||
| config, | ||
| view, | ||
| [(_entity_key(1), {"trips": ValueProto(int64_val=10)}, event_ts, created_ts)], | ||
| None, | ||
| ) | ||
| conn = sqlite3.connect(config.online_store.path) | ||
| try: | ||
| conn.execute( | ||
| f"UPDATE " | ||
| f"{compute_table_id(config.project, view, config.registry.enable_online_feature_view_versioning)} " | ||
| f"SET event_ts = ?, created_ts = ? WHERE event_ts = ?", | ||
| (legacy_event_epoch, legacy_created_epoch, int(event_ts.timestamp())), | ||
| ) | ||
| conn.commit() | ||
| finally: | ||
| conn.close() | ||
|
|
||
| # Reading the legacy row with the UTC adapters shifts it back by the old | ||
| # writer's offset and fails the TTL check, exactly like after an upgrade. | ||
| shift = timedelta(seconds=legacy_event_epoch - int(event_ts.timestamp())) | ||
| read_ts, features = SqliteOnlineStore().online_read(config, view, [_entity_key(1)])[ | ||
| 0 | ||
| ] | ||
| assert features["trips"].int64_val == 10 | ||
| assert read_ts == event_ts + shift | ||
| assert _ttl_status(read_ts, view) == FieldStatus.OUTSIDE_MAX_AGE | ||
|
|
||
| # Materializing a window that starts after the legacy row advances the | ||
| # recorded interval without rewriting rows stored before that interval. | ||
| store.materialize( | ||
| start_date=event_ts + timedelta(hours=2), | ||
| end_date=event_ts + timedelta(hours=3), | ||
| ) | ||
| store.materialize_incremental(end_date=event_ts + timedelta(hours=5)) | ||
| assert _raw_row_for_event_epoch(config, view, legacy_event_epoch) == ( | ||
| legacy_event_epoch, | ||
| legacy_created_epoch, | ||
| ) | ||
| read_ts, _ = SqliteOnlineStore().online_read(config, view, [_entity_key(1)])[0] | ||
| assert read_ts == event_ts + shift | ||
| assert _ttl_status(read_ts, view) == FieldStatus.OUTSIDE_MAX_AGE | ||
|
|
||
| # A full backfill over the legacy row's event time rewrites it as UTC. | ||
| store.materialize( | ||
| start_date=event_ts - timedelta(hours=1), | ||
| end_date=event_ts + timedelta(hours=5), | ||
| ) | ||
| true_event_epoch = int(event_ts.timestamp()) | ||
| assert _raw_row_for_event_epoch(config, view, legacy_event_epoch) is None | ||
| assert _raw_row_for_event_epoch(config, view, true_event_epoch) == ( | ||
| true_event_epoch, | ||
| None, | ||
| ) | ||
| read_ts, features = SqliteOnlineStore().online_read(config, view, [_entity_key(1)])[ | ||
| 0 | ||
| ] | ||
| assert features["trips"].int64_val == 10 | ||
| assert read_ts == event_ts | ||
| assert _ttl_status(read_ts, view) == FieldStatus.PRESENT | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not hasattr(time, "tzset"), reason="time.tzset() is Unix-only") | ||
| def test_adapt_datetime_epoch_treats_naive_datetimes_as_utc(clean_tz_env): | ||
| _set_process_tz("Asia/Shanghai") | ||
| assert adapt_datetime_epoch(datetime(2024, 1, 1)) == 1704067200 | ||
|
|
||
|
|
||
| def test_adapt_datetime_epoch_converts_non_utc_aware_datetimes(): | ||
| offset = timezone(timedelta(hours=8)) | ||
| assert adapt_datetime_epoch(datetime(2024, 1, 1, 8, tzinfo=offset)) == 1704067200 | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not hasattr(time, "tzset"), reason="time.tzset() is Unix-only") | ||
| def test_convert_timestamp_returns_naive_utc(clean_tz_env): | ||
| _set_process_tz("Asia/Shanghai") | ||
| converted = convert_timestamp(b"1704067200") | ||
| assert converted == datetime(2024, 1, 1) | ||
| assert converted.tzinfo is None |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Incorrect timestamps for existing SQLite features
After upgrading in place,
convert_timestampmisreads rows that older versions wrote with a nonzero timezone offset. The old reader reversed that offset on the same host. Now online retrieval can mark fresh features expired or expired features fresh.Learn more
SQLite keeps the latest feature values and their timestamps in an on-disk database. Previously, online_write_batch supplied naive UTC datetimes to an adapter that interpreted them in the writer's local timezone. The old reader reversed that shift when it ran under the same timezone and the conversion round-tripped. update preserves existing tables, so the new converter reads the same integers as UTC. online_read labels the result UTC, and the freshness check uses it without correction. Incremental materialization starts at the last completed interval and does not automatically replay all existing rows.
Example: A Shanghai deployment writes a feature at 05:34 UTC. Before upgrading, it reads back 05:34 UTC. At 05:39 UTC after upgrading, the same row reads back 21:34 UTC on the previous day and returns
OUTSIDE_MAX_AGEfor a one-hour TTL.Recommended fix: Provide an upgrade path that rebuilds the affected online rows from authoritative feature data before the new reader serves them. Document how to rebuild and repopulate the store rather than relying on incremental materialization. Do not infer the original writer's timezone from the current reader's timezone: legacy and corrected epochs have the same integer representation. Add a regression test that writes a row with the legacy adapter and reads it after upgrading.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good callout, and I agree with not trying to infer the original writer timezone in
convert_timestampsince legacy and UTC epochs have the same integer representation.This is the upgrade trade-off noted in
# Misc. Hosts running in UTC are unaffected. For non-UTC hosts upgrading in place with an existing SQLite database, the clean recovery path is to rebuild or run a fullfeast materialize <start> <end>(rather thanfeast materialize-incremental, which only processes new intervals) so existing rows are rewritten with true UTC epochs.Happy to add a short upgrade note in the docs or PR release note if maintainers want to highlight this for non-UTC SQLite deployments.