Skip to content

Commit 8bcb5aa

Browse files
committed
fix: Retry BigQuery entity table expiration on stale etag
The BigQuery offline store sets a 30-minute expiration on the temporary entity table it uploads by calling client.get_table() followed by client.update_table(table, ["expires"]). update_table sends a conditional PATCH keyed on the etag returned by get_table(). Shortly after the job that creates the table completes, BigQuery can still be asynchronously finalizing the table's metadata (e.g. row counts, last modified time), which changes its etag server-side. 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 upload itself succeeded. Because this is a table metadata PATCH rather than a BigQuery job, the failure leaves no trace in the BigQuery Jobs Explorer, making it look spurious and hard to diagnose from the GCP console. Extract the expiration logic into _set_table_expiration() and retry it on PreconditionFailed, refetching the table for a fresh etag before each retry. Signed-off-by: Luis Silva <58522514+luisSilva1234@users.noreply.github.com>
1 parent a291a0f commit 8bcb5aa

2 files changed

Lines changed: 90 additions & 5 deletions

File tree

‎sdk/python/feast/infra/offline_stores/bigquery.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,13 @@
2525
import pyarrow
2626
import pyarrow.parquet
2727
from pydantic import StrictStr, field_validator
28-
from tenacity import Retrying, retry_if_exception_type, stop_after_delay, wait_fixed
28+
from tenacity import (
29+
Retrying,
30+
retry_if_exception_type,
31+
stop_after_attempt,
32+
stop_after_delay,
33+
wait_fixed,
34+
)
2935

3036
from feast import flags_helper
3137
from feast.credentials import get_connection_config_override
@@ -72,7 +78,7 @@
7278

7379
try:
7480
from google.api_core import client_info as http_client_info
75-
from google.api_core.exceptions import NotFound
81+
from google.api_core.exceptions import NotFound, PreconditionFailed
7682
from google.auth.exceptions import DefaultCredentialsError
7783
from google.cloud import bigquery
7884
from google.cloud.bigquery import Client, SchemaField, Table
@@ -1531,13 +1537,39 @@ def _upload_entity_df(
15311537
block_until_done(client, job)
15321538

15331539
# Ensure that the table expires after some time
1534-
table = client.get_table(table=table_name)
1535-
table.expires = _utc_now() + timedelta(minutes=30)
1536-
client.update_table(table, ["expires"])
1540+
table = _set_table_expiration(client, table_name)
15371541

15381542
return table
15391543

15401544

1545+
def _set_table_expiration(client: Client, table_name: str) -> Table:
1546+
"""
1547+
Sets a table to expire 30 minutes from now, retrying on a stale etag.
1548+
1549+
`update_table` sends a conditional PATCH keyed on the table's etag, as returned by
1550+
the preceding `get_table` call. Shortly after the job that creates `table_name`
1551+
completes, BigQuery can still be asynchronously finalizing the table's metadata
1552+
(e.g. row counts, last modified time), which changes its etag. If that happens
1553+
between `get_table` and `update_table`, the PATCH is rejected with a
1554+
`PreconditionFailed` (412, "did not meet condition IF_MATCH") even though the table
1555+
itself was created successfully. Refetching the table for a fresh etag before
1556+
retrying resolves this.
1557+
"""
1558+
1559+
def _try_set_expiration(client: Client, table_name: str) -> Table:
1560+
table = client.get_table(table=table_name)
1561+
table.expires = _utc_now() + timedelta(minutes=30)
1562+
return client.update_table(table, ["expires"])
1563+
1564+
retryer = Retrying(
1565+
wait=wait_fixed(1),
1566+
stop=stop_after_attempt(5),
1567+
retry=retry_if_exception_type(PreconditionFailed),
1568+
reraise=True,
1569+
)
1570+
return retryer(_try_set_expiration, client, table_name)
1571+
1572+
15411573
def _get_entity_schema(
15421574
client: Client, entity_df: Union[pd.DataFrame, str]
15431575
) -> Dict[str, np.dtype]:

‎sdk/python/tests/unit/infra/offline_stores/test_bigquery.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44
import pandas as pd
55
import pyarrow
66
import pytest
7+
from google.api_core.exceptions import PreconditionFailed
78

89
from feast.infra.offline_stores.bigquery import (
910
BigQueryOfflineStore,
1011
BigQueryOfflineStoreConfig,
1112
BigQueryRetrievalJob,
13+
_set_table_expiration,
1214
)
1315
from feast.infra.offline_stores.bigquery_source import BigQuerySource
1416
from feast.infra.online_stores.sqlite import SqliteOnlineStoreConfig
@@ -250,6 +252,57 @@ def test_pull_latest_date_type_with_partition_column(mock_get_bigquery_client):
250252
assert "_PARTITIONDATE <= '2021-01-02'" in actual_query
251253

252254

255+
class TestSetTableExpiration:
256+
def test_succeeds_on_first_attempt(self):
257+
client = Mock()
258+
table = Mock()
259+
client.get_table.return_value = table
260+
client.update_table.return_value = table
261+
262+
result = _set_table_expiration(client, "project.dataset.table")
263+
264+
assert result is table
265+
client.get_table.assert_called_once_with(table="project.dataset.table")
266+
client.update_table.assert_called_once_with(table, ["expires"])
267+
268+
def test_retries_on_stale_etag_then_succeeds(self):
269+
"""
270+
Simulates the race where `update_table`'s conditional PATCH is rejected
271+
because the table's etag changed after `get_table` fetched it (e.g. BigQuery
272+
still finalizing the table's metadata right after the upload job completed).
273+
A refetched table should be retried against until it succeeds.
274+
"""
275+
client = Mock()
276+
stale_table = Mock(name="stale_table")
277+
fresh_table = Mock(name="fresh_table")
278+
client.get_table.side_effect = [stale_table, fresh_table]
279+
client.update_table.side_effect = [
280+
PreconditionFailed("did not meet condition IF_MATCH"),
281+
fresh_table,
282+
]
283+
284+
result = _set_table_expiration(client, "project.dataset.table")
285+
286+
assert result is fresh_table
287+
assert client.get_table.call_count == 2
288+
assert client.update_table.call_count == 2
289+
# The retry must act on the refetched table, not the stale one that
290+
# triggered the PreconditionFailed.
291+
client.update_table.assert_called_with(fresh_table, ["expires"])
292+
293+
def test_gives_up_after_max_attempts(self):
294+
client = Mock()
295+
client.get_table.return_value = Mock()
296+
client.update_table.side_effect = PreconditionFailed(
297+
"did not meet condition IF_MATCH"
298+
)
299+
300+
with pytest.raises(PreconditionFailed):
301+
_set_table_expiration(client, "project.dataset.table")
302+
303+
assert client.update_table.call_count == 5
304+
305+
253306
def test_bigquery_source_date_type_proto_roundtrip():
254307
source = BigQuerySource(
255308
table="project:dataset.table",

0 commit comments

Comments
 (0)