Skip to content

: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.

fix(batch-exports): retry transient Databricks connection failures (#74829)

Ross7f362da7bd3c
diff --git a/products/batch_exports/backend/api/destination_tests/databricks.py b/products/batch_exports/backend/api/destination_tests/databricks.py
index dd6df47ca005..c7d782932d2b 100644
--- a/products/batch_exports/backend/api/destination_tests/databricks.py
+++ b/products/batch_exports/backend/api/destination_tests/databricks.py
@@ -63,6 +63,8 @@ class DatabricksTestStep(DestinationTestStep):
client_secret=self.client_secret,
catalog=self.catalog or "",
schema=self.schema or "",
+ # Interactive connection test, so fail fast instead of backing off for minutes.
+ connect_max_attempts=1,
)
async with client.connect(set_context=False) as databricks_client:
yield databricks_client
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
index a349af7b3713..95fe2f528a7d 100644
--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
@@ -51,7 +51,11 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
-from products.batch_exports.backend.temporal.utils import JsonType, handle_non_retryable_errors
+from products.batch_exports.backend.temporal.utils import (
+ JsonType,
+ handle_non_retryable_errors,
+ make_retryable_with_exponential_backoff,
+)
LOGGER = get_write_only_logger(__name__)
EXTERNAL_LOGGER = get_logger("EXTERNAL")
@@ -91,9 +95,15 @@ SIX_HOURS = 6 * 60 * 60
class DatabricksConnectionError(Exception):
- """Error for Databricks connection."""
+ """Represents an error connecting to Databricks.
- pass
+ `retryable` is False only for failures that definitively indicate invalid configuration,
+ so we don't spend minutes backing off before telling the user to fix their settings.
+ """
+
+ def __init__(self, message: str, retryable: bool = True):
+ super().__init__(message)
+ self.retryable = retryable
class DatabricksIntegrationNotFoundError(Exception):
@@ -219,6 +229,11 @@ class DatabricksClient:
# Timeout (seconds) for the TCP reachability preflight in `_check_host_reachable`.
DEFAULT_CONNECT_TIMEOUT = 30.0
+ # How many times to attempt the initial connection before giving up. Databricks outages are
+ # usually brief, so ~3 minutes of jittered backoff (2s, 8s, 18s, 32s, 32s, ...) resolves most
+ # blips without meaningfully delaying feedback on definitive config errors (not retried).
+ DEFAULT_CONNECT_MAX_ATTEMPTS = 8
+
def __init__(
self,
server_hostname: str,
@@ -229,6 +244,7 @@ class DatabricksClient:
schema: str,
statement_timeout_seconds: float | None = None,
connect_timeout_seconds: float = DEFAULT_CONNECT_TIMEOUT,
+ connect_max_attempts: int = DEFAULT_CONNECT_MAX_ATTEMPTS,
):
self.server_hostname = server_hostname
self.http_path = http_path
@@ -241,6 +257,7 @@ class DatabricksClient:
# server only kicks in as a last resort.
self.statement_timeout_seconds = statement_timeout_seconds
self.connect_timeout_seconds = connect_timeout_seconds
+ self.connect_max_attempts = connect_max_attempts
self._connection: None | Connection = None
@@ -254,6 +271,7 @@ class DatabricksClient:
integration: DatabricksIntegration,
statement_timeout_seconds: float | None = None,
connect_timeout_seconds: float = DEFAULT_CONNECT_TIMEOUT,
+ connect_max_attempts: int = DEFAULT_CONNECT_MAX_ATTEMPTS,
) -> t.Self:
"""Initialize a DatabricksClient from `DatabricksInsertInputs` and `DatabricksIntegration`.
@@ -270,6 +288,7 @@ class DatabricksClient:
schema=inputs.schema,
statement_timeout_seconds=statement_timeout_seconds,
connect_timeout_seconds=connect_timeout_seconds,
+ connect_max_attempts=connect_max_attempts,
)
@property
@@ -301,6 +320,13 @@ class DatabricksClient:
await asyncio.to_thread(probe)
except OSError as err:
self.logger.info("Could not reach Databricks host '%s': %s", self.server_hostname, err)
+ # EAI_NONAME/EAI_FAIL mean the hostname does not exist, so no amount of retrying will
+ # help. Other errors are worth retrying.
+ if isinstance(err, socket.gaierror) and err.errno in (socket.EAI_NONAME, socket.EAI_FAIL):
+ raise DatabricksConnectionError(
+ "Could not resolve Databricks server hostname. Please check that the server hostname is valid.",
+ retryable=False,
+ ) from err
raise DatabricksConnectionError(
"Failed to connect to Databricks. Please check that your connection details are valid."
) from err
@@ -347,7 +373,7 @@ class DatabricksClient:
self.http_path,
)
raise DatabricksConnectionError(
- f"Timed out while trying to connect to Databricks. Please check that the server_hostname and http_path are valid."
+ "Timed out while trying to connect to Databricks. Please check that the server_hostname and http_path are valid."
)
# for some reason, Databricks reports some connection failures as a ValueError
except (ValueError, urllib3.exceptions.HTTPError, urllib3.exceptions.MaxRetryError) as err:
@@ -367,10 +393,32 @@ class DatabricksClient:
self.server_hostname,
self.http_path,
)
+ # Invalid credentials won't fix themselves, anything else (e.g. a
+ # momentarily-unavailable warehouse) is worth retrying.
+ if _is_invalid_credentials_error(err):
+ raise DatabricksConnectionError(
+ "Failed to connect to Databricks: invalid credentials. "
+ "Please check that your client_id and client_secret are valid.",
+ retryable=False,
+ ) from err
raise DatabricksConnectionError(f"Failed to connect to Databricks: {err}") from err
return result
+ async def _connect_with_retries(self) -> Connection:
+ """Establish a connection, retrying transient failures with exponential backoff."""
+
+ def is_retryable(err: Exception) -> bool:
+ return isinstance(err, DatabricksConnectionError) and err.retryable
+
+ connect = make_retryable_with_exponential_backoff(
+ self._connect,
+ max_attempts=self.connect_max_attempts,
+ retryable_exceptions=(DatabricksConnectionError,),
+ is_exception_retryable=is_retryable,
+ )
+ return await connect()
+
@contextlib.asynccontextmanager
async def connect(self, set_context: bool = True):
"""Manage a Databricks connection.
@@ -382,7 +430,7 @@ class DatabricksClient:
"""
self.logger.info("Initializing Databricks connection")
- self._connection = await self._connect()
+ self._connection = await self._connect_with_retries()
self.logger.info("Connected to Databricks")
# Verify the connection is responsive before proceeding
@@ -1043,6 +1091,16 @@ def _is_insufficient_permissions_error(err: DatabaseError) -> bool:
)
+def _is_invalid_credentials_error(err: BaseException) -> bool:
+ """Check if a connect-time error indicates the OAuth credentials are rejected.
+
+ A 5xx error is transient and retryable, but a 401 (and the OAuth "invalid_client"/"unauthorized"
+ markers) means the client_id/client_secret are wrong and retrying won't help.
+ """
+ message = str(err)
+ return "invalid_client" in message or "unauthorized" in message or "Status 401" in message
+
+
@contextlib.asynccontextmanager
async def handle_common_errors(operation: str, timeout: float) -> AsyncGenerator[None]:
"""Map common Databricks client errors to non-retryable typed exceptions.
diff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py
index 04a1146734d0..5b8f38efdea7 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py
@@ -1,12 +1,14 @@
import os
import time
+import socket
import asyncio
import threading
+import dataclasses
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from databricks.sql.exc import RequestError, ServerOperationError
+from databricks.sql.exc import OperationalError, RequestError, ServerOperationError
from products.batch_exports.backend.temporal.destinations.databricks_batch_export import (
DatabricksClient,
@@ -53,6 +55,43 @@ def mock_cursor(client: DatabricksClient) -> MagicMock:
return cursor
+def fast_backoff(monkeypatch):
+ """Speed up the connect-retry backoff so tests don't actually sleep."""
+ monkeypatch.setattr("products.batch_exports.backend.temporal.utils.asyncio.sleep", AsyncMock())
+
+
+class MockDatabricksSqlConnect:
+ """Holder for the mocks a successful ``connect()`` interacts with."""
+
+ sql_connect: MagicMock
+ ping: AsyncMock
+ use_catalog: AsyncMock
+ use_schema: AsyncMock
+
+
+def mock_sql_connect(client: DatabricksClient):
+ """Patch the SDK's ``sql.connect`` plus the post-connect lifecycle calls."""
+
+ with (
+ patch(
+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",
+ return_value=MagicMock(),
+ ) as sql_connect_mock,
+ patch.object(client, "ping", new=AsyncMock()) as ping_mock,
+ patch.object(client, "use_catalog", new=AsyncMock()) as use_catalog_mock,
+ patch.object(client, "use_schema", new=AsyncMock()) as use_schema_mock,
+ ):
+ yield MockDatabricksSqlConnect(
+ sql_connect=sql_connect_mock,
+ ping=ping_mock,
+ use_catalog=use_catalog_mock,
+ use_schema=use_schema_mock,
+ )
+
+
class TestExecuteQuery:
@pytest.mark.parametrize("trigger", ["cancellation", "timeout"])
async def test_cancels_cursor_on_cancellation_or_timeout(
@@ -138,7 +177,7 @@ class TestConnect:
use_catalog_mock.assert_not_called()
- async def test_when_invalid_host(self):
+ async def test_when_invalid_host(self, client: DatabricksClient, mock_sql_connect: MockDatabricksSqlConnect):
"""An invalid/unreachable host must fail fast rather than hang for ~5 minutes in the SDK's
OIDC discovery (https://github.com/databricks/databricks-sdk-py/issues/1046).
@@ -148,27 +187,89 @@ class TestConnect:
"""
# 192.0.2.1 is reserved as non-routable (RFC 5737 TEST-NET-1), so the preflight connect fails
# fast (no DNS, no real host).
- client = DatabricksClient(
- server_hostname="192.0.2.1",
- http_path="test",
- client_id="test",
- client_secret="test",
- catalog="test",
- schema="test",
- connect_timeout_seconds=0.01,
- )
+ client.server_hostname = "192.0.2.1"
+ client.connect_timeout_seconds = 0.01
+ client.connect_max_attempts = 1
+
+ with pytest.raises(
+ DatabricksConnectionError,
+ match="Failed to connect to Databricks. Please check that your connection details are valid.",
+ ):
+ async with client.connect():
+ pass
+
+ mock_sql_connect.sql_connect.assert_not_called()
+
+ async def test_retries_transient_connection_failure(
+ self, client: DatabricksClient, fast_backoff, mock_sql_connect: MockDatabricksSqlConnect
+ ):
+ """A transient DNS blip must not permanently fail the run: connect() should retry until the
+ host becomes reachable, then complete the connection."""
+ attempts = {"n": 0}
+
+ def reachability_result(*_args, **_kwargs):
+ attempts["n"] += 1
+ if attempts["n"] < 3:
+ raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
+ return MagicMock()
with patch(
- "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect"
- ) as mock_sql_connect:
- with pytest.raises(
- DatabricksConnectionError,
- match="Failed to connect to Databricks. Please check that your connection details are valid.",
- ):
- async with client.connect():
- pass
+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.socket.create_connection",
+ side_effect=reachability_result,
+ ):
+ async with client.connect():
+ pass
+
+ assert attempts["n"] == 3
+ mock_sql_connect.use_catalog.assert_called_once()
+
+ @pytest.mark.parametrize(
+ "errno,expected_match",
+ [
+ (socket.EAI_NONAME, "Could not resolve Databricks server hostname"),
+ (socket.EAI_FAIL, "Could not resolve Databricks server hostname"),
+ ],
+ )
+ async def test_does_not_retry_unresolvable_hostname(
+ self,
+ client: DatabricksClient,
+ fast_backoff,
+ mock_sql_connect: MockDatabricksSqlConnect,
+ errno: int,
+ expected_match: str,
+ ):
+ """A hostname that does not exist is a config error, so we should fail fast with a targeted
+ message instead of backing off for minutes."""
+ create_connection_mock = MagicMock(side_effect=socket.gaierror(errno, "Name or service not known"))
+
+ with (
+ patch(
+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.socket.create_connection",
+ new=create_connection_mock,
+ ),
+ pytest.raises(DatabricksConnectionError, match=expected_match),
+ ):
+ async with client.connect():
+ pass
+
+ assert create_connection_mock.call_count == 1
+ mock_sql_connect.sql_connect.assert_not_called()
+
+ async def test_does_not_retry_invalid_credentials(
+ self, client: DatabricksClient, fast_backoff, mock_sql_connect: MockDatabricksSqlConnect
+ ):
+ """Rejected OAuth credentials are a config error, so we should fail fast rather than keep
+ hammering the token endpoint."""
+ mock_sql_connect.sql_connect.side_effect = OperationalError("Failed to fetch OAuth token: invalid_client")
+
+ with (
+ patch.object(client, "_check_host_reachable", new=AsyncMock()),
+ pytest.raises(DatabricksConnectionError, match="invalid credentials"),
+ ):
+ async with client.connect():
+ pass
- mock_sql_connect.assert_not_called()
+ assert mock_sql_connect.sql_connect.call_count == 1
class TestQueryBuilders: