- Notifications
You must be signed in to change notification settings - Fork126
Add retry mechanism to telemetry requests#617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
3 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
71 changes: 70 additions & 1 deletionsrc/databricks/sql/common/http.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletionssrc/databricks/sql/exc.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
6 changes: 4 additions & 2 deletionssrc/databricks/sql/telemetry/telemetry_client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,9 @@ | ||
| import threading | ||
| import time | ||
| import logging | ||
| from concurrent.futures import ThreadPoolExecutor | ||
| from typing import Dict, Optional | ||
| from databricks.sql.common.http import TelemetryHttpClient | ||
| from databricks.sql.telemetry.models.event import ( | ||
| TelemetryEvent, | ||
| DriverSystemConfiguration, | ||
| @@ -159,6 +159,7 @@ def __init__( | ||
| self._driver_connection_params = None | ||
| self._host_url = host_url | ||
| self._executor = executor | ||
| self._http_client = TelemetryHttpClient.get_instance() | ||
| def _export_event(self, event): | ||
| """Add an event to the batch queue and flush if batch is full""" | ||
| @@ -207,7 +208,7 @@ def _send_telemetry(self, events): | ||
| try: | ||
| logger.debug("Submitting telemetry request to thread pool") | ||
| future = self._executor.submit( | ||
| self._http_client.post, | ||
saishreeeee marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| url, | ||
| data=request.to_json(), | ||
| headers=headers, | ||
| @@ -433,6 +434,7 @@ def close(session_id_hex): | ||
| ) | ||
| try: | ||
| TelemetryClientFactory._executor.shutdown(wait=True) | ||
| TelemetryHttpClient.close() | ||
| except Exception as e: | ||
| logger.debug("Failed to shutdown thread pool executor: %s", e) | ||
| TelemetryClientFactory._executor = None | ||
3 changes: 1 addition & 2 deletionstests/unit/test_telemetry.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletionstests/unit/test_telemetry_retry.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import pytest | ||
| from unittest.mock import patch, MagicMock | ||
| import io | ||
| import time | ||
| from databricks.sql.telemetry.telemetry_client import TelemetryClientFactory | ||
| from databricks.sql.auth.retry import DatabricksRetryPolicy | ||
| PATCH_TARGET = 'urllib3.connectionpool.HTTPSConnectionPool._get_conn' | ||
| def create_mock_conn(responses): | ||
| """Creates a mock connection object whose getresponse() method yields a series of responses.""" | ||
| mock_conn = MagicMock() | ||
| mock_http_responses = [] | ||
| for resp in responses: | ||
| mock_http_response = MagicMock() | ||
| mock_http_response.status = resp.get("status") | ||
| mock_http_response.headers = resp.get("headers", {}) | ||
| body = resp.get("body", b'{}') | ||
| mock_http_response.fp = io.BytesIO(body) | ||
| def release(): | ||
| mock_http_response.fp.close() | ||
| mock_http_response.release_conn = release | ||
| mock_http_responses.append(mock_http_response) | ||
| mock_conn.getresponse.side_effect = mock_http_responses | ||
| return mock_conn | ||
| class TestTelemetryClientRetries: | ||
| @pytest.fixture(autouse=True) | ||
| def setup_and_teardown(self): | ||
| TelemetryClientFactory._initialized = False | ||
| TelemetryClientFactory._clients = {} | ||
| TelemetryClientFactory._executor = None | ||
| yield | ||
| if TelemetryClientFactory._executor: | ||
| TelemetryClientFactory._executor.shutdown(wait=True) | ||
| TelemetryClientFactory._initialized = False | ||
| TelemetryClientFactory._clients = {} | ||
| TelemetryClientFactory._executor = None | ||
| def get_client(self, session_id, num_retries=3): | ||
| """ | ||
| Configures a client with a specific number of retries. | ||
| """ | ||
| TelemetryClientFactory.initialize_telemetry_client( | ||
| telemetry_enabled=True, | ||
| session_id_hex=session_id, | ||
| auth_provider=None, | ||
| host_url="test.databricks.com", | ||
| ) | ||
| client = TelemetryClientFactory.get_telemetry_client(session_id) | ||
| retry_policy = DatabricksRetryPolicy( | ||
| delay_min=0.01, | ||
| delay_max=0.02, | ||
| stop_after_attempts_duration=2.0, | ||
| stop_after_attempts_count=num_retries, | ||
| delay_default=0.1, | ||
| force_dangerous_codes=[], | ||
| urllib3_kwargs={'total': num_retries} | ||
| ) | ||
| adapter = client._http_client.session.adapters.get("https://") | ||
| adapter.max_retries = retry_policy | ||
| return client | ||
| @pytest.mark.parametrize( | ||
| "status_code, description", | ||
| [ | ||
| (401, "Unauthorized"), | ||
| (403, "Forbidden"), | ||
| (501, "Not Implemented"), | ||
| (200, "Success"), | ||
| ], | ||
| ) | ||
| def test_non_retryable_status_codes_are_not_retried(self, status_code, description): | ||
| """ | ||
| Verifies that terminal error codes (401, 403, 501) and success codes (200) are not retried. | ||
| """ | ||
| # Use the status code in the session ID for easier debugging if it fails | ||
| client = self.get_client(f"session-{status_code}") | ||
| mock_responses = [{"status": status_code}] | ||
| with patch(PATCH_TARGET, return_value=create_mock_conn(mock_responses)) as mock_get_conn: | ||
| client.export_failure_log("TestError", "Test message") | ||
| TelemetryClientFactory.close(client._session_id_hex) | ||
| mock_get_conn.return_value.getresponse.assert_called_once() | ||
| def test_exceeds_retry_count_limit(self): | ||
| """ | ||
| Verifies that the client retries up to the specified number of times before giving up. | ||
| Verifies that the client respects the Retry-After header and retries on 429, 502, 503. | ||
| """ | ||
| num_retries = 3 | ||
| expected_total_calls = num_retries + 1 | ||
| retry_after = 1 | ||
| client = self.get_client("session-exceed-limit", num_retries=num_retries) | ||
| mock_responses = [{"status": 503, "headers": {"Retry-After": str(retry_after)}}, {"status": 429}, {"status": 502}, {"status": 503}] | ||
| with patch(PATCH_TARGET, return_value=create_mock_conn(mock_responses)) as mock_get_conn: | ||
| start_time = time.time() | ||
| client.export_failure_log("TestError", "Test message") | ||
| TelemetryClientFactory.close(client._session_id_hex) | ||
| end_time = time.time() | ||
| assert mock_get_conn.return_value.getresponse.call_count == expected_total_calls | ||
| assert end_time - start_time > retry_after |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.