Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/reference/online-stores/sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <start_ts> <end_ts>` 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).
Expand Down
8 changes: 5 additions & 3 deletions sdk/python/feast/infra/online_stores/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())


Expand All @@ -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)
Comment on lines +107 to +108

Copy link
Copy Markdown
Contributor

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_timestamp misreads 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_AGE for 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

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_timestamp since 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 full feast materialize <start> <end> (rather than feast 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.



sqlite3.register_converter("date", convert_date)
Expand Down
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