From 0cb1f591286d1abb83a4d085c739686935e93f36 Mon Sep 17 00:00:00 2001 From: PandaAB <104823169+PandaAB@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:52:04 +0800 Subject: [PATCH 1/2] fix: Use UTC in SQLite online store timestamp adapters adapt_datetime_epoch interpreted naive datetimes in the process local timezone and convert_timestamp returned local wall clock time, so a database written on a non-UTC host stored event_ts and created_ts offset by the local UTC offset, and a reader in another timezone got shifted timestamps that made TTL checks report fresh rows as OUTSIDE_MAX_AGE. Treat naive datetimes as UTC in adapt_datetime_epoch and return naive UTC datetimes from convert_timestamp, matching the naive means UTC contract of to_naive_utc and make_tzaware. Rows already written by non-UTC hosts keep their shifted epochs and are not migrated automatically. Add regression tests that flip the process TZ between the write and read sides, assert the on-disk epochs equal the true UTC epochs, and check TTL status through the production TTL path. Signed-off-by: PandaAB <104823169+PandaAB@users.noreply.github.com> --- .../feast/infra/online_stores/sqlite.py | 8 +- .../test_sqlite_utc_timestamps.py | 175 ++++++++++++++++++ 2 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py diff --git a/sdk/python/feast/infra/online_stores/sqlite.py b/sdk/python/feast/infra/online_stores/sqlite.py index 98d89fe2c4d..36cf7a5a58d 100644 --- a/sdk/python/feast/infra/online_stores/sqlite.py +++ b/sdk/python/feast/infra/online_stores/sqlite.py @@ -82,7 +82,9 @@ def adapt_datetime_iso(val: datetime): def adapt_datetime_epoch(val: datetime): - """Adapt datetime.datetime to Unix timestamp.""" + """Adapt datetime.datetime to a Unix timestamp, treating naive values as UTC.""" + if val.tzinfo is None: + val = val.replace(tzinfo=timezone.utc) return int(val.timestamp()) @@ -102,8 +104,8 @@ def convert_datetime(val: bytes): def convert_timestamp(val: bytes): - """Convert Unix epoch timestamp to datetime.datetime object.""" - return datetime.fromtimestamp(int(val)) + """Convert a Unix epoch timestamp to a naive UTC datetime.""" + return datetime.fromtimestamp(int(val), tz=timezone.utc).replace(tzinfo=None) sqlite3.register_converter("date", convert_date) diff --git a/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py b/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py new file mode 100644 index 00000000000..a3643f5e937 --- /dev/null +++ b/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py @@ -0,0 +1,175 @@ +"""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 pytest + +from feast import Entity, 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 +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 _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_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 From 0d3712942c06b93a9b8b26ac04aa2ef856bb6212 Mon Sep 17 00:00:00 2001 From: PandaAB <104823169+PandaAB@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:28:07 +0800 Subject: [PATCH 2/2] docs: Document SQLite UTC upgrade path and test legacy recovery Add an upgrade note to the SQLite online store reference explaining that event_ts and created_ts are now stored as UTC, that environments which already ran in UTC are unaffected, and that non-UTC environments need to rebuild the SQLite file or run a full feast materialize backfill over the existing data, while feast materialize-incremental never rewrites rows stored before its interval. Add a regression test that seeds a row the way the old local-time adapter wrote it, verifies that the UTC adapters read it back shifted and outside the TTL window, verifies that materialize-incremental leaves it untouched, and verifies that a full materialize backfill restores the true UTC epoch and a PRESENT status. Signed-off-by: PandaAB <104823169+PandaAB@users.noreply.github.com> --- docs/reference/online-stores/sqlite.md | 8 + .../test_sqlite_utc_timestamps.py | 140 +++++++++++++++++- 2 files changed, 146 insertions(+), 2 deletions(-) diff --git a/docs/reference/online-stores/sqlite.md b/docs/reference/online-stores/sqlite.md index 859702c07f1..dfc08ea97d6 100644 --- a/docs/reference/online-stores/sqlite.md +++ b/docs/reference/online-stores/sqlite.md @@ -22,6 +22,14 @@ online_store: The full set of configuration options is available in [SqliteOnlineStoreConfig](https://rtd.feast.dev/en/latest/#feast.infra.online_stores.sqlite.SqliteOnlineStoreConfig). +## Upgrading from local-time timestamps + +The SQLite online store now reads and writes the `event_ts` / `created_ts` Unix timestamps as UTC. Older versions resolved timezone-naive timestamps in the process local timezone when writing, so what is already on disk depends on where the rows were written: + +* Environments that already ran in the UTC timezone are not affected, since the stored epochs already match UTC. +* On non-UTC environments the epochs of previously written rows are shifted by the local UTC offset. The old writer's timezone cannot be recovered from the stored integers, so an in-place upgrade cannot repair existing SQLite database files automatically. Rebuild the SQLite database file, or run a full backfill with `feast materialize ` covering the time range of the existing data to rewrite the old rows as UTC. +* `feast materialize-incremental` only writes the interval after the last completed materialization and does not rewrite rows stored before it, so it cannot recover legacy rows on its own. + ## Functionality Matrix The set of functionality supported by online stores is described in detail [here](overview.md#functionality). diff --git a/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py b/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py index a3643f5e937..d5330ae6e05 100644 --- a/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py +++ b/sdk/python/tests/unit/infra/online_store/test_sqlite_utc_timestamps.py @@ -11,9 +11,17 @@ import time from datetime import datetime, timedelta, timezone +import pandas as pd import pytest -from feast import Entity, FeatureView, Field, FileSource, RepoConfig +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, @@ -28,7 +36,7 @@ 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 +from feast.utils import _populate_response_from_feature_data, to_naive_utc from feast.value_type import ValueType TRIPS_VALUE = 7 @@ -71,6 +79,20 @@ def _stored_epochs(config: RepoConfig, view: FeatureView): 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() @@ -156,6 +178,120 @@ def test_sqlite_online_store_utc_epochs_across_timezones( 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")