Skip to content

Commit 4452725

Browse files
committed
wait for _flush before closing HTTP client
1 parent 76ce5ce commit 4452725

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/databricks/sql/telemetry/telemetry_client.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import json
55
from concurrent.futures import ThreadPoolExecutor
66
from concurrent.futures import Future
7+
from concurrent.futures import wait
78
from datetime import datetime, timezone
89
from typing import List, Dict, Any, Optional, TYPE_CHECKING
910
from databricks.sql.telemetry.models.event import (
@@ -182,6 +183,7 @@ def __init__(
182183
self._user_agent = None
183184
self._events_batch = []
184185
self._lock = threading.RLock()
186+
self._pending_futures = set()
185187
self._driver_connection_params = None
186188
self._host_url = host_url
187189
self._executor = executor
@@ -245,6 +247,9 @@ def _send_telemetry(self, events):
245247
timeout=900,
246248
)
247249

250+
with self._lock:
251+
self._pending_futures.add(future)
252+
248253
future.add_done_callback(
249254
lambda fut: self._telemetry_request_callback(fut, sent_count=sent_count)
250255
)
@@ -303,6 +308,9 @@ def _telemetry_request_callback(self, future, sent_count: int):
303308

304309
except Exception as e:
305310
logger.debug("Telemetry request failed with exception: %s", e)
311+
finally:
312+
with self._lock:
313+
self._pending_futures.discard(future)
306314

307315
def _export_telemetry_log(self, **telemetry_event_kwargs):
308316
"""
@@ -356,9 +364,20 @@ def export_latency_log(self, latency_ms, sql_execution_event, sql_statement_id):
356364
)
357365

358366
def close(self):
359-
"""Flush remaining events before closing"""
367+
"""Flush remaining events and wait for them to complete before closing"""
360368
logger.debug("Closing TelemetryClient for connection %s", self._session_id_hex)
361369
self._flush()
370+
371+
with self._lock:
372+
futures_to_wait_on = list(self._pending_futures)
373+
374+
if futures_to_wait_on:
375+
logger.debug(
376+
"Waiting for %s pending telemetry requests to complete.",
377+
len(futures_to_wait_on),
378+
)
379+
wait(futures_to_wait_on)
380+
362381
self._http_client.close()
363382

364383

0 commit comments

Comments
 (0)