Skip to content

Commit 9954f0c

Browse files
committed
test: isolate retry HTTP mocks from background telemetry
Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
1 parent 0c1b9e8 commit 9954f0c

2 files changed

Lines changed: 114 additions & 125 deletions

File tree

‎tests/e2e/common/retry_test_mixins.py‎

Lines changed: 26 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
from contextlib import contextmanager
2+
import threading
23
import time
34
from typing import Optional, List
45
from unittest.mock import MagicMock, PropertyMock, patch
56
import io
67

78
import pytest
9+
from urllib3.connectionpool import HTTPSConnectionPool
810
from urllib3.exceptions import MaxRetryError
911

1012
from databricks.sql.auth.retry import DatabricksRetryPolicy
@@ -15,97 +17,22 @@
1517
SessionAlreadyClosedError,
1618
UnsafeToRetryError,
1719
)
18-
from databricks.sql.telemetry.telemetry_client import (
19-
NoopTelemetryClient,
20-
TelemetryClient,
21-
TelemetryClientFactory,
22-
_TelemetryClientHolder,
23-
)
2420

2521

2622
@contextmanager
27-
def _isolated_from_telemetry():
28-
# Tests that mock urllib3 globally (via _get_conn / _validate_conn) also
29-
# intercept background telemetry pushes from the shared
30-
# TelemetryClientFactory executor — inflating mock.call_count and breaking
31-
# assertions like `call_count == 6`. Three layers of defence:
32-
#
33-
# 1. Drain TelemetryClientFactory and override initialize_telemetry_client
34-
# so new connections install NoopTelemetryClient (which submits nothing).
35-
# 2. Patch TelemetryClient._send_telemetry to a no-op as a backstop — covers
36-
# any real TelemetryClient instance that slips in (e.g. a stale module-
37-
# global, a code path that bypasses initialize_telemetry_client, or
38-
# anything created before this context entered).
39-
# 3. Patch TelemetryClient._export_event to a no-op so even if a real
40-
# client receives an event, the event never reaches the queue and the
41-
# flush logic never fires.
42-
#
43-
# Without layer 2/3 we have observed `/telemetry-ext` requests showing up
44-
# in merge_group runs (concurrent CI load on the warehouse stresses paths
45-
# that single-test runs don't hit), inflating retry-test counts and
46-
# producing flaky AssertionErrors.
47-
with TelemetryClientFactory._lock:
48-
saved_clients = TelemetryClientFactory._clients
49-
saved_executor = TelemetryClientFactory._executor
50-
saved_initialized = TelemetryClientFactory._initialized
51-
for holder in list(saved_clients.values()):
52-
try:
53-
holder.client.close()
54-
except Exception:
55-
pass
56-
if saved_executor is not None:
57-
try:
58-
TelemetryClientFactory._stop_flush_thread()
59-
saved_executor.shutdown(wait=True)
60-
except Exception:
61-
pass
62-
TelemetryClientFactory._clients = {}
63-
TelemetryClientFactory._executor = None
64-
TelemetryClientFactory._initialized = False
65-
66-
def _install_noop(*args, host_url=None, **kwargs):
67-
host_url = TelemetryClientFactory.getHostUrlSafely(host_url)
68-
with TelemetryClientFactory._lock:
69-
TelemetryClientFactory._clients[host_url] = _TelemetryClientHolder(
70-
NoopTelemetryClient()
71-
)
23+
def _mock_pool_method(method_name):
24+
"""Mock synchronous test requests without intercepting background telemetry."""
25+
original = getattr(HTTPSConnectionPool, method_name)
26+
test_thread = threading.current_thread()
27+
mock_method = MagicMock()
7228

73-
def _noop_send(self, events):
74-
return None
75-
76-
def _noop_export(self, event):
77-
return None
78-
79-
try:
80-
def _noop_send_with_unified_client(self, *args, **kwargs):
81-
return None
82-
83-
with patch.object(
84-
TelemetryClientFactory,
85-
"initialize_telemetry_client",
86-
staticmethod(_install_noop),
87-
), patch.object(
88-
TelemetryClient, "_send_telemetry", _noop_send
89-
), patch.object(
90-
TelemetryClient, "_export_event", _noop_export
91-
), patch.object(
92-
# Backstop layer 4: no-op the actual HTTP boundary. _send_telemetry
93-
# only suppresses NEW submissions; a future already submitted (e.g. by
94-
# the holder.client.close() flush above, which runs before these
95-
# patches apply) still calls _send_with_unified_client on a background
96-
# thread and would hit the network inside the test's urllib3 mock.
97-
# Patching the HTTP method itself closes that already-submitted-future
98-
# gap for any caller of this helper.
99-
TelemetryClient,
100-
"_send_with_unified_client",
101-
_noop_send_with_unified_client,
102-
):
103-
yield
104-
finally:
105-
with TelemetryClientFactory._lock:
106-
TelemetryClientFactory._clients = saved_clients
107-
TelemetryClientFactory._executor = saved_executor
108-
TelemetryClientFactory._initialized = saved_initialized
29+
def dispatch(pool, *args, **kwargs):
30+
if threading.current_thread() is test_thread:
31+
return mock_method(*args, **kwargs)
32+
return original(pool, *args, **kwargs)
33+
34+
with patch.object(HTTPSConnectionPool, method_name, dispatch):
35+
yield mock_method
10936

11037

11138
class Client429ResponseMixin:
@@ -260,7 +187,7 @@ def mocked_server_response(
260187

261188
mock_response = SimpleHttpResponse(status, headers, redirect_location)
262189

263-
with patch("urllib3.connectionpool.HTTPSConnectionPool._get_conn") as getconn_mock:
190+
with _mock_pool_method("_get_conn") as getconn_mock:
264191
getconn_mock.return_value.getresponse.return_value = mock_response
265192
try:
266193
yield getconn_mock
@@ -288,7 +215,7 @@ def mock_sequential_server_responses(responses: List[dict]):
288215
for resp in responses
289216
]
290217

291-
with patch("urllib3.connectionpool.HTTPSConnectionPool._get_conn") as getconn_mock:
218+
with _mock_pool_method("_get_conn") as getconn_mock:
292219
getconn_mock.return_value.getresponse.side_effect = mock_responses
293220
try:
294221
yield getconn_mock
@@ -306,21 +233,7 @@ class PySQLRetryTestsMixin:
306233
"_retry_stop_after_attempts_count": 5,
307234
"_retry_stop_after_attempts_duration": 30,
308235
"_retry_delay_default": 0.5,
309-
# Disable telemetry on every retry-count test. These tests patch urllib3
310-
# globally (HTTPSConnectionPool._get_conn / _validate_conn) and assert the
311-
# connection's own request was retried exactly N times. With telemetry on
312-
# (the default), the same connection makes two kinds of side-channel HTTP
313-
# calls through the same mocked pool that inflate the count and flake the
314-
# assertion:
315-
# 1. A synchronous feature-flag GET during Connection.__init__
316-
# (is_telemetry_enabled -> FeatureFlagsContext._refresh_flags), and
317-
# 2. Async telemetry POSTs to /telemetry-ext from the background executor
318-
# and the periodic flush thread.
319-
# enable_telemetry=False short-circuits is_telemetry_enabled before the
320-
# feature-flag fetch and installs a NoopTelemetryClient, removing both
321-
# sources at their origin without changing the retry behavior under test.
322-
# Every test in this mixin merges _retry_policy into its connection params,
323-
# so setting it here covers them all. See also _isolated_from_telemetry().
236+
# Avoid synchronous feature-flag requests during connection setup.
324237
"enable_telemetry": False,
325238
}
326239

@@ -331,10 +244,7 @@ class PySQLRetryTestsMixin:
331244
{"use_sea": True},
332245
],
333246
)
334-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
335-
def test_retry_urllib3_settings_are_honored(
336-
self, mock_send_telemetry, extra_params
337-
):
247+
def test_retry_urllib3_settings_are_honored(self, extra_params):
338248
"""Databricks overrides some of urllib3's configuration. This tests confirms that what configuration
339249
we DON'T override is preserved in urllib3's internals
340250
"""
@@ -361,12 +271,9 @@ def test_retry_urllib3_settings_are_honored(
361271
{"use_sea": True},
362272
],
363273
)
364-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
365-
def test_oserror_retries(self, mock_send_telemetry, extra_params):
274+
def test_oserror_retries(self, extra_params):
366275
"""If a network error occurs during make_request, the request is retried according to policy"""
367-
with _isolated_from_telemetry(), patch(
368-
"urllib3.connectionpool.HTTPSConnectionPool._validate_conn",
369-
) as mock_validate_conn:
276+
with _mock_pool_method("_validate_conn") as mock_validate_conn:
370277
mock_validate_conn.side_effect = OSError("Some arbitrary network error")
371278
with pytest.raises(MaxRetryError) as cm:
372279
extra_params = {**extra_params, **self._retry_policy}
@@ -382,14 +289,13 @@ def test_oserror_retries(self, mock_send_telemetry, extra_params):
382289
{"use_sea": True},
383290
],
384291
)
385-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
386-
def test_retry_max_count_not_exceeded(self, mock_send_telemetry, extra_params):
292+
def test_retry_max_count_not_exceeded(self, extra_params):
387293
"""GIVEN the max_attempts_count is 5
388294
WHEN the server sends nothing but 429 responses
389295
THEN the connector issues six request (original plus five retries)
390296
before raising an exception
391297
"""
392-
with _isolated_from_telemetry(), mocked_server_response(
298+
with mocked_server_response(
393299
status=429, headers={"Retry-After": "0"}
394300
) as mock_obj:
395301
with pytest.raises(MaxRetryError) as cm:
@@ -405,8 +311,7 @@ def test_retry_max_count_not_exceeded(self, mock_send_telemetry, extra_params):
405311
{"use_sea": True},
406312
],
407313
)
408-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
409-
def test_retry_exponential_backoff(self, mock_send_telemetry, extra_params):
314+
def test_retry_exponential_backoff(self, extra_params):
410315
"""GIVEN the retry policy is configured for reasonable exponential backoff
411316
WHEN the server sends nothing but 429 responses with retry-afters
412317
THEN the connector will use those retry-afters values as floor
@@ -415,7 +320,7 @@ def test_retry_exponential_backoff(self, mock_send_telemetry, extra_params):
415320
retry_policy["_retry_delay_min"] = 1
416321

417322
time_start = time.time()
418-
with _isolated_from_telemetry(), mocked_server_response(
323+
with mocked_server_response(
419324
status=429, headers={"Retry-After": "8"}
420325
) as mock_obj:
421326
with pytest.raises(RequestError) as cm:
@@ -636,10 +541,7 @@ def test_retry_abort_close_operation_on_404(self, extra_params, caplog):
636541
{"use_sea": True},
637542
],
638543
)
639-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
640-
def test_3xx_redirect_codes_are_not_retried(
641-
self, mock_send_telemetry, extra_params
642-
):
544+
def test_3xx_redirect_codes_are_not_retried(self, extra_params):
643545
"""GIVEN the connector is configured with a custom max_redirects
644546
WHEN the DatabricksRetryPolicy receives a 302 redirect
645547
THEN the connector does not retry since 3xx codes are not retried per policy
@@ -672,9 +574,8 @@ def test_3xx_redirect_codes_are_not_retried(
672574
{"use_sea": True},
673575
],
674576
)
675-
@patch("databricks.sql.telemetry.telemetry_client.TelemetryClient._send_telemetry")
676577
def test_3xx_codes_not_retried_regardless_of_max_redirects_setting(
677-
self, mock_send_telemetry, extra_params
578+
self, extra_params
678579
):
679580
"""GIVEN the connector is configured without a custom max_redirects
680581
WHEN the DatabricksRetryPolicy receives a 302 redirect
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from concurrent.futures import ThreadPoolExecutor
2+
from contextlib import contextmanager
3+
from threading import Event
4+
from unittest.mock import MagicMock, patch
5+
6+
import pytest
7+
from urllib3.connectionpool import HTTPSConnectionPool
8+
from urllib3.exceptions import MaxRetryError
9+
from urllib3.util.retry import Retry
10+
11+
from tests.e2e.common.retry_test_mixins import (
12+
SimpleHttpResponse,
13+
_mock_pool_method,
14+
mocked_server_response,
15+
mock_sequential_server_responses,
16+
)
17+
18+
19+
@contextmanager
20+
def _offline_pool():
21+
connection = MagicMock()
22+
connection.close.return_value = None
23+
connection.getresponse.side_effect = lambda: SimpleHttpResponse(200, {})
24+
with HTTPSConnectionPool("example.invalid") as pool, patch.object(
25+
pool, "_new_conn", return_value=connection
26+
):
27+
yield pool
28+
29+
30+
@pytest.fixture
31+
def pending_telemetry():
32+
ready, release = Event(), Event()
33+
34+
def send(pool):
35+
ready.set()
36+
assert release.wait(timeout=5)
37+
return pool.urlopen("POST", "/telemetry-ext", retries=False)
38+
39+
with _offline_pool() as pool, ThreadPoolExecutor(max_workers=1) as executor:
40+
future = executor.submit(send, pool)
41+
assert ready.wait(timeout=5)
42+
try:
43+
yield future, release
44+
finally:
45+
release.set()
46+
47+
48+
@pytest.mark.parametrize("sequential", [False, True])
49+
def test_background_telemetry_does_not_consume_retry_responses(
50+
pending_telemetry, sequential
51+
):
52+
responses = [
53+
{"status": 429, "headers": {"Retry-After": "0"}, "redirect_location": None},
54+
{"status": 503, "headers": {}, "redirect_location": None},
55+
]
56+
mock_response = (
57+
mock_sequential_server_responses(responses)
58+
if sequential
59+
else mocked_server_response(status=429, headers={"Retry-After": "0"})
60+
)
61+
future, release = pending_telemetry
62+
with _offline_pool() as pool, mock_response as mocked_connection:
63+
release.set()
64+
assert future.result(timeout=5).status == 200
65+
mocked_connection.assert_not_called()
66+
67+
with pytest.raises(MaxRetryError):
68+
pool.urlopen(
69+
"POST",
70+
"/sql",
71+
retries=Retry(
72+
total=1, status_forcelist=[429, 503], allowed_methods=None
73+
),
74+
)
75+
assert mocked_connection.return_value.getresponse.call_count == 2
76+
77+
78+
def test_background_telemetry_does_not_receive_retry_errors(pending_telemetry):
79+
future, release = pending_telemetry
80+
with _offline_pool() as pool, _mock_pool_method("_validate_conn") as validate:
81+
validate.side_effect = OSError("Some arbitrary network error")
82+
release.set()
83+
assert future.result(timeout=5).status == 200
84+
validate.assert_not_called()
85+
86+
with pytest.raises(MaxRetryError):
87+
pool.urlopen("POST", "/sql", retries=Retry(total=1, allowed_methods=None))
88+
assert validate.call_count == 2

0 commit comments

Comments
 (0)