Skip to content

Commit 59c0ec5

Browse files
committed
chore: Add cleanup step for old UDFs in anonymous dataset
1 parent 60b28bf commit 59c0ec5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

bigframes/blob/_functions.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,19 @@
1313
# limitations under the License.
1414

1515
from dataclasses import dataclass
16+
import datetime
1617
import inspect
1718
from typing import Callable, Iterable, Union
19+
import warnings
1820

1921
import google.cloud.bigquery as bigquery
2022

23+
import bigframes.exceptions as bfe
2124
import bigframes.session
2225
import bigframes.session._io.bigquery as bf_io_bigquery
2326

2427
_PYTHON_TO_BQ_TYPES = {int: "INT64", float: "FLOAT64", str: "STRING", bytes: "BYTES"}
28+
_UDF_CLEANUP_THRESHOLD_DAYS = 3
2529

2630

2731
@dataclass(frozen=True)
@@ -66,12 +70,39 @@ def _output_bq_type(self):
6670
sig = inspect.signature(self._func)
6771
return _PYTHON_TO_BQ_TYPES[sig.return_annotation]
6872

73+
def _cleanup_old_udfs(self):
74+
"""Clean up old UDFs in the anonymous dataset."""
75+
dataset = self._session._anon_dataset_manager.dataset
76+
routines = list(self._session.bqclient.list_routines(dataset))
77+
seven_days_ago = datetime.datetime.now(
78+
datetime.timezone.utc
79+
) - datetime.timedelta(days=_UDF_CLEANUP_THRESHOLD_DAYS)
80+
81+
cleaned_up_routines = 0
82+
for routine in routines:
83+
if (
84+
routine.created < seven_days_ago
85+
and routine._properties["routineType"] == "SCALAR_FUNCTION"
86+
):
87+
self._session.bqclient.delete_routine(routine.reference)
88+
cleaned_up_routines += 1
89+
6990
def _create_udf(self):
7091
"""Create Python UDF in BQ. Return name of the UDF."""
7192
udf_name = str(
7293
self._session._anon_dataset_manager.generate_unique_resource_id()
7394
)
7495

96+
# Try to clean up the old Python UDFs in the anonymous dataset. Do not
97+
# raise an error when it fails for this step.
98+
try:
99+
self._cleanup_old_udfs()
100+
except Exception as e:
101+
msg = bfe.format_message(
102+
f"Failed to clean up the old Python UDFs before creating {udf_name}: {e}"
103+
)
104+
warnings.warn(msg, category=bfe.CleanupFailedWarning)
105+
75106
func_body = inspect.getsource(self._func)
76107
func_name = self._func.__name__
77108
packages = str(list(self._requirements))

bigframes/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class UnknownLocationWarning(Warning):
3030

3131

3232
class CleanupFailedWarning(Warning):
33-
"""Bigframes failed to clean up a table resource."""
33+
"""Bigframes failed to clean up a table or function resource."""
3434

3535

3636
class DefaultIndexWarning(Warning):

0 commit comments

Comments
 (0)