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
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
from typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union

import dill
import fsspec
Expand Down Expand Up @@ -775,16 +775,10 @@ def join_batch_with_features(batch: pd.DataFrame) -> pd.DataFrame:
).reset_index(drop=True)

try:
# Only the feature rows are deduplicated. Every entity row is
# a separate request, so rows that share an entity key and a
# timestamp are all kept (merge_asof matches each of them).
if feature_join_keys:
batch_dedup_cols = [
k for k in entity_join_keys if k in batch_sorted.columns
]
if timestamp_field in batch_sorted.columns:
batch_dedup_cols.append(timestamp_field)
if batch_dedup_cols:
batch_sorted = batch_sorted.drop_duplicates(
subset=batch_dedup_cols, keep="last"
)
feature_dedup_cols = [
k for k in feature_join_keys if k in features_sorted.columns
]
Expand Down Expand Up @@ -1244,6 +1238,14 @@ def schema(self) -> pa.Schema:
return pa.Table.from_pandas(df).schema


def _unused_column_name(column: str, existing_columns: Set[str]) -> str:
"""Return a temporary name for a source column that collides with request data."""
name = f"__{column}"
while name in existing_columns:
name = f"_{name}"
return name


def _make_filter_range(timestamp_field: str, start_date: datetime, end_date: datetime):
# Why: factory function for time-range filtering in Ray map_batches
def _filter_range(batch: pd.DataFrame) -> pd.Series:
Expand Down Expand Up @@ -2355,6 +2357,8 @@ def get_historical_features(
for k, v in mapping.items():
global_field_mappings[v] = k

# Request columns after any rename below, to keep internal names unused.
entity_columns = set(entity_df_sample.columns)
if global_field_mappings:
cols_to_rename = {
v: k
Expand All @@ -2363,7 +2367,12 @@ def get_historical_features(
}
if cols_to_rename:
entity_ds = apply_field_mapping(entity_ds, cols_to_rename)
entity_columns = {
cols_to_rename.get(col, col) for col in entity_df_sample.columns
}

# Columns that earlier feature views add to the result.
added_columns: Set[str] = set()
result_ds = entity_ds
for fv in regular_feature_views:
fv_feature_refs = [
Expand Down Expand Up @@ -2498,15 +2507,39 @@ def apply_transformation_with_serialized_func(
# Also map requested_feats back to logical names after forward mapping
requested_feats = [field_mapping.get(f, f) for f in requested_feats]

# The joins below use one timestamp column name for both sides. If
# the request has its own column named like the source timestamp
# field, join on an internal name instead, so the request's values
# are not used as the point-in-time cutoff.
join_timestamp_field = timestamp_field
if (
timestamp_field != "event_timestamp"
and timestamp_field not in entity_df_sample.columns
and timestamp_field in entity_df_sample.columns
and "event_timestamp" in entity_df_sample.columns
):
join_timestamp_field = _unused_column_name(
timestamp_field,
set(entity_df_sample.columns)
| entity_columns
| added_columns
| set(join_keys)
| set(original_join_keys)
| set(requested_feats)
| ({created_col} if created_col else set()),
)
feature_ds = apply_field_mapping(
feature_ds, {timestamp_field: join_timestamp_field}
)

if (
join_timestamp_field != "event_timestamp"
and join_timestamp_field not in entity_df_sample.columns
and "event_timestamp" in entity_df_sample.columns
):

def add_timestamp_field(
batch: pd.DataFrame,
timestamp_field: str = timestamp_field,
timestamp_field: str = join_timestamp_field,
) -> pd.DataFrame:
batch = batch.copy()
batch[timestamp_field] = batch["event_timestamp"]
Expand All @@ -2515,7 +2548,7 @@ def add_timestamp_field(
result_ds = result_ds.map_batches(
add_timestamp_field, batch_format="pandas"
)
result_ds = normalize_timestamp_columns(result_ds, timestamp_field)
result_ds = normalize_timestamp_columns(result_ds, join_timestamp_field)

if store._resource_manager is None:
raise ValueError("Resource manager not initialized")
Expand All @@ -2531,7 +2564,7 @@ def add_timestamp_field(
)
feature_df = feature_ds.to_pandas()
feature_df = ensure_timestamp_compatibility(
feature_df, [timestamp_field]
feature_df, [join_timestamp_field]
)

if store._data_processor is None:
Expand All @@ -2540,7 +2573,7 @@ def add_timestamp_field(
result_ds,
feature_df,
join_keys,
timestamp_field,
join_timestamp_field,
requested_feats,
full_feature_names,
fv.projection.name_to_use(),
Comment on lines 2573 to 2579

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.

🔴 Shared cutoff drops distinct requests

After the cutoff switch, broadcast_join_features drops all but one same-batch request sharing an entity key and event timestamp. This happens when merge_asof succeeds, even if distinct values in the colliding request column previously kept the rows separate.

(Refers to this code)

Learn more

Each entity dataframe row is a separate request for historical features and can carry its own request data. The new collision path copies event_timestamp to the join key instead of using the colliding request column as that key. For small sources, broadcast entity deduplication keeps only the last row per entity key and join timestamp in each batch. A successful merge_asof receives that reduced batch, so the other requests never reach the result. The manual fallback uses the original cleaned batch instead and does not exhibit this particular row loss.

Example: Request features for driver 1 twice at Jan 3, with request IDs 101 and 102 and request ts values of Jan 2 and Jan 4. A small source with one row for driver 1 at Jan 1 takes the successful broadcast merge path. Before this change both IDs survived; now only 102 survives. Both IDs need the Jan 1 feature value.

Recommended fix: Keep the entity rows intact for the collision path when calling merge_asof. Leave source-side deduplication in place. Add a regression test with two request IDs, identical entity keys and event timestamps, different colliding request values, and a source ordered so that merge_asof succeeds.

Devin Review


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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in ab071f7. The row loss came from the entity-side drop_duplicates in broadcast_join_features. It also dropped rows on master without any collision (two requests for the same entity and event time came back as one; DuckDB returns both), so I removed it instead of narrowing it. The feature-side dedup is unchanged.

Added test_requests_sharing_entity_and_event_timestamp_are_all_kept (separate request ids, same entity and event time, with and without different colliding ts values). It fails on the previous head and passes now. Ray component and universal tests pass, and sending every request twice now returns every result twice in 171 random cases (one or two feature views, full feature names, a field mapping and a join-key map); master lost duplicates in 87 of them.

Expand All @@ -2553,7 +2586,7 @@ def add_timestamp_field(
f"Using distributed join for {fv.name} (size: {feature_size // 1024**2}MB)"
)
feature_ds = ensure_timestamp_compatibility(
feature_ds, [timestamp_field]
feature_ds, [join_timestamp_field]
)

if store._data_processor is None:
Expand All @@ -2562,7 +2595,7 @@ def add_timestamp_field(
result_ds,
feature_ds,
join_keys,
timestamp_field,
join_timestamp_field,
requested_feats,
window_size=config.offline_store.window_size_for_joins,
full_feature_names=full_feature_names,
Expand All @@ -2572,6 +2605,24 @@ def add_timestamp_field(
else None,
)

if join_timestamp_field != timestamp_field:

def drop_join_timestamp_field(
batch: pd.DataFrame,
join_timestamp_field: str = join_timestamp_field,
) -> pd.DataFrame:
return batch.drop(columns=[join_timestamp_field], errors="ignore")

result_ds = result_ds.map_batches(
drop_join_timestamp_field, batch_format="pandas"
)

added_columns.add(timestamp_field)
added_columns.update(
f"{fv.projection.name_to_use()}__{feat}" if full_feature_names else feat
for feat in requested_feats
)

def finalize_result(batch: pd.DataFrame) -> pd.DataFrame:
batch = batch.copy()

Expand Down
140 changes: 140 additions & 0 deletions sdk/python/tests/component/ray/test_ray_timestamp_field_collision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Ray offline store: request columns named like the source timestamp field.

The entity dataframe can hold request data in a column that has the same name
as a feature view's source timestamp field. That column is not the event
timestamp, so retrieval must not use it as the point-in-time cutoff, and it
must come back unchanged, whatever its type.
"""

from datetime import timedelta
from pathlib import Path

import pandas as pd
import pytest

from feast import Entity, FeatureStore, FeatureView, Field, FileSource, RepoConfig
from feast.infra.ray_initializer import shutdown_ray
from feast.types import Int64
from feast.value_type import ValueType


@pytest.fixture(autouse=True)
def fresh_ray():
shutdown_ray()
yield
shutdown_ray()


def _feature_store(repo: Path, with_driver_2: bool = True) -> FeatureStore:
# Driver 1 has 10, 20 and 30 on 1, 2 and 3 Jan; driver 2 has 40 on 1 Jan.
trips_df = pd.DataFrame(
{
"driver_id": [1, 1, 1, 2],
"ts": pd.to_datetime(
["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-01"], utc=True
),
"trips": [10, 20, 30, 40],
}
)
if not with_driver_2:
# With one driver the source timestamps stay sorted after sorting by
# driver, so the broadcast join uses merge_asof instead of falling
# back to its row-by-row join.
trips_df = trips_df[trips_df["driver_id"] == 1]
trips_df.to_parquet(repo / "trips.parquet")
driver = Entity(name="driver", join_keys=["driver_id"], value_type=ValueType.INT64)
trips = FeatureView(
name="driver_trips",
entities=[driver],
schema=[Field(name="trips", dtype=Int64)],
source=FileSource(path=str(repo / "trips.parquet"), timestamp_field="ts"),
ttl=timedelta(days=7),
)
store = FeatureStore(
config=RepoConfig(
project="ray_timestamp_field_collision",
provider="local",
registry=str(repo / "registry.db"),
offline_store={"type": "ray", "storage_path": str(repo / "ray_storage")},
online_store={"type": "sqlite", "path": str(repo / "online.db")},
entity_key_serialization_version=3,
repo_path=str(repo),
)
)
store.apply([driver, trips])
return store


@pytest.mark.parametrize(
"request_values",
[
pd.to_datetime(
["2024-01-10 00:00", "2023-12-25 00:00", "2024-01-02 06:00"], utc=True
),
pd.Series([1, 2, 3], dtype="int64"),
pd.Series(["a", "2024-01-05", ""], dtype=object),
],
ids=["datetime", "int", "string"],
)
@pytest.mark.parametrize("full_feature_names", [False, True], ids=lambda v: str(v))
def test_request_column_named_like_timestamp_field(
tmp_path, request_values, full_feature_names
):
store = _feature_store(tmp_path)
entity_df = pd.DataFrame(
{
"driver_id": [1, 1, 2],
"event_timestamp": pd.to_datetime(
["2024-01-02 12:00", "2024-01-02 13:00", "2024-01-02 12:00"], utc=True
),
"ts": list(request_values),
"request_id": [1, 2, 3],
}
)

result = store.get_historical_features(
entity_df=entity_df,
features=["driver_trips:trips"],
full_feature_names=full_feature_names,
).to_df()

feature = "driver_trips__trips" if full_feature_names else "trips"
assert set(result.columns) == set(entity_df.columns) | {feature}
result = result.sort_values("request_id").reset_index(drop=True)
# The latest value at or before each event timestamp.
assert result[feature].tolist() == [20, 20, 40]
# The request column comes back unchanged.
assert result["ts"].tolist() == entity_df["ts"].tolist()


@pytest.mark.parametrize(
"with_colliding_column", [True, False], ids=["colliding-ts", "no-collision"]
)
def test_requests_sharing_entity_and_event_timestamp_are_all_kept(
tmp_path, with_colliding_column
):
store = _feature_store(tmp_path, with_driver_2=False)
entity_df = pd.DataFrame(
{
"driver_id": [1, 1],
"event_timestamp": pd.to_datetime(
["2024-01-02 12:00", "2024-01-02 12:00"], utc=True
),
"request_id": [101, 102],
}
)
if with_colliding_column:
# Different request values in the column named like the source timestamp.
entity_df["ts"] = pd.to_datetime(["2024-01-02", "2024-01-04"], utc=True)

result = store.get_historical_features(
entity_df=entity_df, features=["driver_trips:trips"]
).to_df()

result = result.sort_values("request_id").reset_index(drop=True)
# Each row is its own request, so both come back, each with the latest value
# at or before its event timestamp.
assert result["request_id"].tolist() == [101, 102]
assert result["trips"].tolist() == [20, 20]
if with_colliding_column:
assert result["ts"].tolist() == entity_df["ts"].tolist()
Original file line number Diff line number Diff line change
Expand Up @@ -1146,15 +1146,8 @@ def test_historical_features_filter_by_created_timestamp(environment):
@pytest.mark.universal_offline_stores
@pytest.mark.parametrize("full_feature_names", [True, False], ids=lambda v: str(v))
def test_historical_features_with_request_column_named_like_timestamp_field(
request, environment, full_feature_names
environment, full_feature_names
):
if environment.data_source_creator.__class__.__name__ == "RayDataSourceCreator":
request.applymarker(
pytest.mark.xfail(
reason="Ray uses the request column as the cutoff: https://github.com/feast-dev/feast/issues/7190",
strict=True,
)
)
store = environment.feature_store

now = datetime.now().replace(microsecond=0, second=0, minute=0)
Expand Down
Loading