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
42 changes: 37 additions & 5 deletions sdk/python/feast/infra/offline_stores/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@
import pyarrow
import pyarrow.parquet
from pydantic import StrictStr, field_validator
from tenacity import Retrying, retry_if_exception_type, stop_after_delay, wait_fixed
from tenacity import (
Retrying,
retry_if_exception_type,
stop_after_attempt,
stop_after_delay,
wait_fixed,
)

from feast import flags_helper
from feast.credentials import get_connection_config_override
Expand Down Expand Up @@ -72,7 +78,7 @@

try:
from google.api_core import client_info as http_client_info
from google.api_core.exceptions import NotFound
from google.api_core.exceptions import NotFound, PreconditionFailed
from google.auth.exceptions import DefaultCredentialsError
from google.cloud import bigquery
from google.cloud.bigquery import Client, SchemaField, Table
Expand Down Expand Up @@ -1531,13 +1537,39 @@ def _upload_entity_df(
block_until_done(client, job)

# Ensure that the table expires after some time
table = client.get_table(table=table_name)
table.expires = _utc_now() + timedelta(minutes=30)
client.update_table(table, ["expires"])
table = _set_table_expiration(client, table_name)

return table


def _set_table_expiration(client: Client, table_name: str) -> Table:
"""
Sets a table to expire 30 minutes from now, retrying on a stale etag.

`update_table` sends a conditional PATCH keyed on the table's etag, as returned by
the preceding `get_table` call. Shortly after the job that creates `table_name`
completes, BigQuery can still be asynchronously finalizing the table's metadata
(e.g. row counts, last modified time), which changes its etag. If that happens
between `get_table` and `update_table`, the PATCH is rejected with a
`PreconditionFailed` (412, "did not meet condition IF_MATCH") even though the table
itself was created successfully. Refetching the table for a fresh etag before
retrying resolves this.
"""

def _try_set_expiration(client: Client, table_name: str) -> Table:
table = client.get_table(table=table_name)
table.expires = _utc_now() + timedelta(minutes=30)
return client.update_table(table, ["expires"])

retryer = Retrying(
wait=wait_fixed(1),
stop=stop_after_attempt(5),
retry=retry_if_exception_type(PreconditionFailed),
reraise=True,
)
return retryer(_try_set_expiration, client, table_name)


def _get_entity_schema(
client: Client, entity_df: Union[pd.DataFrame, str]
) -> Dict[str, np.dtype]:
Expand Down
53 changes: 53 additions & 0 deletions sdk/python/tests/unit/infra/offline_stores/test_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import pandas as pd
import pyarrow
import pytest
from google.api_core.exceptions import PreconditionFailed

from feast.infra.offline_stores.bigquery import (
BigQueryOfflineStore,
BigQueryOfflineStoreConfig,
BigQueryRetrievalJob,
_set_table_expiration,
)
from feast.infra.offline_stores.bigquery_source import BigQuerySource
from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig
Expand Down Expand Up @@ -250,6 +252,57 @@ def test_pull_latest_date_type_with_partition_column(mock_get_bigquery_client):
assert "_PARTITIONDATE <= '2021-01-02'" in actual_query


class TestSetTableExpiration:
def test_succeeds_on_first_attempt(self):
client = Mock()
table = Mock()
client.get_table.return_value = table
client.update_table.return_value = table

result = _set_table_expiration(client, "project.dataset.table")

assert result is table
client.get_table.assert_called_once_with(table="project.dataset.table")
client.update_table.assert_called_once_with(table, ["expires"])

def test_retries_on_stale_etag_then_succeeds(self):
"""
Simulates the race where `update_table`'s conditional PATCH is rejected
because the table's etag changed after `get_table` fetched it (e.g. BigQuery
still finalizing the table's metadata right after the upload job completed).
A refetched table should be retried against until it succeeds.
"""
client = Mock()
stale_table = Mock(name="stale_table")
fresh_table = Mock(name="fresh_table")
client.get_table.side_effect = [stale_table, fresh_table]
client.update_table.side_effect = [
PreconditionFailed("did not meet condition IF_MATCH"),
fresh_table,
]

result = _set_table_expiration(client, "project.dataset.table")

assert result is fresh_table
assert client.get_table.call_count == 2
assert client.update_table.call_count == 2
# The retry must act on the refetched table, not the stale one that
# triggered the PreconditionFailed.
client.update_table.assert_called_with(fresh_table, ["expires"])

def test_gives_up_after_max_attempts(self):
client = Mock()
client.get_table.return_value = Mock()
client.update_table.side_effect = PreconditionFailed(
"did not meet condition IF_MATCH"
)

with pytest.raises(PreconditionFailed):
_set_table_expiration(client, "project.dataset.table")

assert client.update_table.call_count == 5


def test_bigquery_source_date_type_proto_roundtrip():
source = BigQuerySource(
table="project:dataset.table",
Expand Down
Loading