:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(databricks): retry transient SSL peer-close on connect (#73613)
Tom Owers722106ac974f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.pyindex 5acda1b7f3f0..405e941e8aa7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py@@ -9,6 +9,7 @@ PostHog-layer wrapper that holds an instance and validates credentials.from __future__ import annotations+import timeimport collectionsfrom collections.abc import Callable, Iteratorfrom contextlib import contextmanager@@ -67,6 +68,43 @@ DATABRICKS_SYSTEM_SCHEMA = "information_schema"# files behind the cursor, so this only bounds how many rows we materialize per yielded batch.DEFAULT_DATABRICKS_FETCH_SIZE = 10_000+# Number of times `connect` will open a fresh Databricks SQL connection before giving up. Mirrors+# the MySQL/Postgres sources' own in-process connect retry budget.+_MAX_CONNECT_ATTEMPTS = 5++# The connector's own request-retry loop (`ThriftBackend.make_request`) only retries HTTP 429/503+# responses and `GetOperationStatus` polling failures — a bare SSL error raised while opening the+# session (including fetching the initial OAuth service-principal token from `/oidc/v1/token`) is+# classified non-retryable and raised immediately on the first attempt. `[SSL:+# UNEXPECTED_EOF_WHILE_READING]` is the peer closing the TLS connection mid-handshake — an+# overloaded endpoint, a proxy/load-balancer idle cull, or a momentary network blip, all of which a+# fresh attempt recovers from. Mirrors the MySQL source's `_is_transient_connect_drop`.+_SSL_UNEXPECTED_EOF_TOKEN = "[SSL: UNEXPECTED_EOF_WHILE_READING]"+++def _is_transient_connect_ssl_eof(e: BaseException) -> bool:+ """Return True if connect failed on a transient SSL peer-close mid-handshake."""+ return isinstance(e, databricks_sql.Error) and _SSL_UNEXPECTED_EOF_TOKEN in str(e)+++def _connect_with_transient_retry(**kwargs: Any) -> Any:+ """Open a Databricks SQL connection, retrying a transient SSL peer-close on connect."""+ attempt = 0+ while True:+ try:+ return databricks_sql.connect(**kwargs)+ except Exception as e:+ attempt += 1+ if attempt >= _MAX_CONNECT_ATTEMPTS or not _is_transient_connect_ssl_eof(e):+ raise+ structlog.get_logger().warning(+ "Transient Databricks connection error during connect; retrying",+ attempt=attempt,+ max_attempts=_MAX_CONNECT_ATTEMPTS,+ exc_info=e,+ )+ time.sleep(min(2 * attempt, 30))+def filter_databricks_incremental_fields(columns: list[tuple[str, str, bool]],@@ -160,7 +198,7 @@ class DatabricksImplementation(SQLSourceImplementation[DatabricksSourceConfig, Aauth_connect_args = {"access_token": config.auth_type.access_token}log_connection_open(db_host=host, via="vendor_https")- connection = databricks_sql.connect(+ connection = _connect_with_transient_retry(server_hostname=host,http_path=config.http_path,catalog=config.catalog,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.pyindex 19f47dac008c..252bd821e64f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.py@@ -2,6 +2,7 @@ import pytestfrom unittest.mock import MagicMock, patchimport pyarrow as pa+from databricks.sql.exc import RequestErrorfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import TableStats@@ -19,6 +20,13 @@ from products.warehouse_sources.backend.types import IncrementalFieldType_CONNECT_PATH = ("products.warehouse_sources.backend.temporal.data_imports.sources.databricks.databricks.databricks_sql.connect")+_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.databricks.databricks.time.sleep"++_SSL_EOF_ERROR_MSG = (+ "Error during request to server: HTTPSConnectionPool(host='x', port=443): Max retries exceeded"+ " with url: /oidc/v1/token (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING]"+ " EOF occurred in violation of protocol')))"+)# ---------------------------------------------------------------------------# Helpers@@ -183,6 +191,34 @@ class TestConnect:raise RuntimeError("boom")mock_connect.return_value.close.assert_called_once()+ def test_transient_ssl_eof_on_connect_is_retried(self, impl):+ # The connector's own retry loop treats a bare SSL error during `open_session` (including+ # the OAuth token fetch) as non-retryable and raises immediately — connect() must recover+ # a transient peer-close instead of failing the sync on the first blip.+ mock_conn = MagicMock()+ with patch(_CONNECT_PATH, side_effect=[RequestError(_SSL_EOF_ERROR_MSG, {}, "x"), mock_conn]) as mock_connect:+ with patch(_SLEEP_PATH):+ with impl.connect(_make_config()) as conn:+ assert conn is mock_conn+ assert mock_connect.call_count == 2++ def test_transient_ssl_eof_exhausts_retries_and_raises(self, impl):+ with patch(_CONNECT_PATH, side_effect=RequestError(_SSL_EOF_ERROR_MSG, {}, "x")) as mock_connect:+ with patch(_SLEEP_PATH):+ with pytest.raises(RequestError):+ with impl.connect(_make_config()):+ pass+ assert mock_connect.call_count == 5++ def test_non_transient_connect_error_is_not_retried(self, impl):+ # A permission/config error must surface on the first attempt — only the specific+ # transient SSL peer-close signature is worth retrying.+ with patch(_CONNECT_PATH, side_effect=RequestError("[PERMISSION_DENIED] nope", {}, "x")) as mock_connect:+ with pytest.raises(RequestError):+ with impl.connect(_make_config()):+ pass+ assert mock_connect.call_count == 1+# ---------------------------------------------------------------------------# Listing methods — they take a pre-opened connection