Skip to content

Commit 0a4e245

Browse files
feat: Add component to manage temporary tables (#1559)
1 parent 0cc6784 commit 0a4e245

File tree

3 files changed

+293
-0
lines changed

3 files changed

+293
-0
lines changed

bigframes/session/bigquery_session.py

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import datetime
16+
import logging
17+
import threading
18+
from typing import Callable, Optional, Sequence
19+
import uuid
20+
21+
# TODO: Non-ibis implementation
22+
import bigframes_vendored.ibis.backends.bigquery.datatypes as ibis_bq
23+
import google.cloud.bigquery as bigquery
24+
25+
from bigframes.core.compile import googlesql
26+
27+
KEEPALIVE_QUERY_TIMEOUT_SECONDS = 5.0
28+
29+
KEEPALIVE_FREQUENCY = datetime.timedelta(hours=6)
30+
31+
32+
logger = logging.getLogger(__name__)
33+
34+
35+
class SessionResourceManager:
36+
"""
37+
Responsible for allocating and cleaning up temporary gbq tables used by a BigFrames session.
38+
"""
39+
40+
def __init__(
41+
self, bqclient: bigquery.Client, location: str, *, kms_key: Optional[str] = None
42+
):
43+
self.bqclient = bqclient
44+
self.location = location
45+
self._kms_key = kms_key
46+
self._session_id: Optional[str] = None
47+
self._sessiondaemon: Optional[RecurringTaskDaemon] = None
48+
self._session_lock = threading.RLock()
49+
50+
def create_temp_table(
51+
self, schema: Sequence[bigquery.SchemaField], cluster_cols: Sequence[str] = []
52+
) -> bigquery.TableReference:
53+
"""Create a temporary session table. Session is an exclusive resource, so throughput is limited"""
54+
# Can't set a table in _SESSION as destination via query job API, so we
55+
# run DDL, instead.
56+
with self._session_lock:
57+
table_ref = bigquery.TableReference(
58+
bigquery.DatasetReference(self.bqclient.project, "_SESSION"),
59+
uuid.uuid4().hex,
60+
)
61+
job_config = bigquery.QueryJobConfig(
62+
connection_properties=[
63+
bigquery.ConnectionProperty("session_id", self._get_session_id())
64+
]
65+
)
66+
if self._kms_key:
67+
job_config.destination_encryption_configuration = (
68+
bigquery.EncryptionConfiguration(kms_key_name=self._kms_key)
69+
)
70+
71+
ibis_schema = ibis_bq.BigQuerySchema.to_ibis(list(schema))
72+
73+
fields = [
74+
f"{googlesql.identifier(name)} {ibis_bq.BigQueryType.from_ibis(ibis_type)}"
75+
for name, ibis_type in ibis_schema.fields.items()
76+
]
77+
fields_string = ",".join(fields)
78+
79+
cluster_string = ""
80+
if cluster_cols:
81+
cluster_cols_sql = ", ".join(
82+
f"{googlesql.identifier(cluster_col)}"
83+
for cluster_col in cluster_cols
84+
)
85+
cluster_string = f"\nCLUSTER BY {cluster_cols_sql}"
86+
87+
ddl = f"CREATE TEMP TABLE `_SESSION`.{googlesql.identifier(table_ref.table_id)} ({fields_string}){cluster_string}"
88+
89+
job = self.bqclient.query(ddl, job_config=job_config)
90+
91+
job.result()
92+
# return the fully qualified table, so it can be used outside of the session
93+
return job.destination
94+
95+
def close(self):
96+
if self._sessiondaemon is not None:
97+
self._sessiondaemon.stop()
98+
99+
if self._session_id is not None and self.bqclient is not None:
100+
self.bqclient.query_and_wait(f"CALL BQ.ABORT_SESSION('{self._session_id}')")
101+
102+
def _get_session_id(self) -> str:
103+
if self._session_id:
104+
return self._session_id
105+
with self._session_lock:
106+
if self._session_id is None:
107+
job_config = bigquery.QueryJobConfig(create_session=True)
108+
# Make sure the session is a new one, not one associated with another query.
109+
job_config.use_query_cache = False
110+
query_job = self.bqclient.query(
111+
"SELECT 1", job_config=job_config, location=self.location
112+
)
113+
query_job.result() # blocks until finished
114+
assert query_job.session_info is not None
115+
assert query_job.session_info.session_id is not None
116+
self._session_id = query_job.session_info.session_id
117+
self._sessiondaemon = RecurringTaskDaemon(
118+
task=self._keep_session_alive, frequency=KEEPALIVE_FREQUENCY
119+
)
120+
self._sessiondaemon.start()
121+
return query_job.session_info.session_id
122+
else:
123+
return self._session_id
124+
125+
def _keep_session_alive(self):
126+
# bq sessions will default expire after 24 hours of disuse, but if queried, this is renewed to a maximum of 7 days
127+
with self._session_lock:
128+
job_config = bigquery.QueryJobConfig(
129+
connection_properties=[
130+
bigquery.ConnectionProperty("session_id", self._get_session_id())
131+
]
132+
)
133+
try:
134+
self.bqclient.query_and_wait(
135+
"SELECT 1",
136+
location=self.location,
137+
job_config=job_config,
138+
wait_timeout=KEEPALIVE_QUERY_TIMEOUT_SECONDS,
139+
)
140+
except Exception as e:
141+
logging.warning("BigQuery session keep-alive query errored : %s", e)
142+
143+
144+
class RecurringTaskDaemon:
145+
def __init__(self, task: Callable[[], None], frequency: datetime.timedelta):
146+
self._stop_event = threading.Event()
147+
self._frequency = frequency
148+
self._thread = threading.Thread(target=self._run_loop, daemon=True)
149+
self._task = task
150+
151+
def start(self):
152+
"""Start the daemon. Cannot be restarted once stopped."""
153+
if self._stop_event.is_set():
154+
raise RuntimeError("Cannot restart daemon thread.")
155+
self._thread.start()
156+
157+
def _run_loop(self):
158+
while True:
159+
self._stop_event.wait(self._frequency.total_seconds())
160+
if self._stop_event.is_set():
161+
return
162+
try:
163+
self._task()
164+
except Exception as e:
165+
logging.warning("RecurringTaskDaemon task errorred: %s", e)
166+
167+
def stop(self, timeout_seconds: Optional[float] = None):
168+
"""Stop and cleanup the daemon."""
169+
if self._thread.is_alive():
170+
self._stop_event.set()
171+
self._thread.join(timeout=timeout_seconds)
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from concurrent.futures import ThreadPoolExecutor
16+
17+
import google
18+
import google.api_core.exceptions
19+
import google.cloud
20+
from google.cloud import bigquery
21+
import pytest
22+
23+
from bigframes.session import bigquery_session
24+
25+
TEST_SCHEMA = [
26+
bigquery.SchemaField("bool field", "BOOLEAN"),
27+
bigquery.SchemaField("string field", "STRING"),
28+
bigquery.SchemaField("float array_field", "FLOAT", mode="REPEATED"),
29+
bigquery.SchemaField(
30+
"struct field",
31+
"RECORD",
32+
fields=(bigquery.SchemaField("int subfield", "INTEGER"),),
33+
),
34+
]
35+
36+
37+
@pytest.fixture
38+
def session_resource_manager(
39+
bigquery_client,
40+
) -> bigquery_session.SessionResourceManager:
41+
return bigquery_session.SessionResourceManager(bigquery_client, "US")
42+
43+
44+
def test_bq_session_create_temp_table_clustered(bigquery_client: bigquery.Client):
45+
session_resource_manager = bigquery_session.SessionResourceManager(
46+
bigquery_client, "US"
47+
)
48+
cluster_cols = ["string field", "bool field"]
49+
50+
session_table_ref = session_resource_manager.create_temp_table(
51+
TEST_SCHEMA, cluster_cols=cluster_cols
52+
)
53+
session_resource_manager._keep_session_alive()
54+
55+
result_table = bigquery_client.get_table(session_table_ref)
56+
assert result_table.schema == TEST_SCHEMA
57+
assert result_table.clustering_fields == cluster_cols
58+
59+
session_resource_manager.close()
60+
with pytest.raises(google.api_core.exceptions.NotFound):
61+
bigquery_client.get_table(session_table_ref)
62+
63+
64+
def test_bq_session_create_multi_temp_tables(bigquery_client: bigquery.Client):
65+
session_resource_manager = bigquery_session.SessionResourceManager(
66+
bigquery_client, "US"
67+
)
68+
69+
def create_table():
70+
return session_resource_manager.create_temp_table(TEST_SCHEMA)
71+
72+
with ThreadPoolExecutor() as executor:
73+
results = [executor.submit(create_table) for i in range(10)]
74+
75+
for future in results:
76+
table = future.result()
77+
result_table = bigquery_client.get_table(table)
78+
assert result_table.schema == TEST_SCHEMA
79+
80+
session_resource_manager.close()

tests/unit/test_daemon.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import datetime
16+
import time
17+
from unittest.mock import MagicMock
18+
19+
from bigframes.session.bigquery_session import RecurringTaskDaemon
20+
21+
22+
def test_recurring_task_daemon_calls():
23+
mock_task = MagicMock()
24+
daemon = RecurringTaskDaemon(
25+
task=mock_task, frequency=datetime.timedelta(seconds=0.1)
26+
)
27+
daemon.start()
28+
time.sleep(1.0)
29+
daemon.stop()
30+
time.sleep(0.5)
31+
# be lenient, but number of calls should be in this ballpark regardless of scheduling hiccups
32+
assert mock_task.call_count > 6
33+
assert mock_task.call_count < 12
34+
35+
36+
def test_recurring_task_daemon_never_started():
37+
mock_task = MagicMock()
38+
_ = RecurringTaskDaemon(
39+
task=mock_task, frequency=datetime.timedelta(seconds=0.0001)
40+
)
41+
time.sleep(0.1)
42+
assert mock_task.call_count == 0

0 commit comments

Comments
 (0)