: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(batch-exports): cancel hanging Databricks queries on timeout/cancellation (#59058)
Rossf80f0908ee29
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex bc3262b2dff9..304ecbc9ec0f 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -14,15 +14,9 @@ from django.conf import settingsimport pyarrow as paimport urllib3.exceptionsfrom databricks import sql-from databricks.sdk._base_client import _BaseClient-from databricks.sdk.core import Config, ConfigAttribute, oauth_service_principal-from databricks.sdk.oauth import (- OidcEndpoints,- get_account_endpoints,- get_azure_entra_id_workspace_endpoints,- get_workspace_endpoints,-)-from databricks.sql.client import Connection+from databricks.sdk.core import Config+from databricks.sdk.credentials_provider import oauth_service_principal+from databricks.sql.client import Connection, Cursorfrom databricks.sql.exc import DatabaseError, OperationalError, ServerOperationErrorfrom databricks.sql.types import Rowfrom structlog.contextvars import bind_contextvars@@ -84,6 +78,13 @@ NON_RETRYABLE_ERROR_TYPES: list[str] = [DatabricksField = tuple[str, str]+# Common operation timeouts (seconds)+ONE_MINUTE = 60+FIVE_MINUTES = 5 * 60+THIRTY_MINUTES = 30 * 60+ONE_HOUR = 60 * 60+SIX_HOURS = 6 * 60 * 60+class DatabricksConnectionError(Exception):"""Error for Databricks connection."""@@ -179,48 +180,6 @@ class DatabricksInsertInputs(BatchExportInsertInputs):use_automatic_schema_evolution: bool = True-class DatabricksConfig(Config):- """Config for Databricks.-- We need to override the oidc_endpoints method to use a custom client with a custom timeout since the default- implementation uses an unconfigurable timeout of 5 minutes. This means our code just hangs if the user provides- invalid connection parameters.-- I have opened an issue with Databricks to make this timeout configurable:- https://github.com/databricks/databricks-sdk-py/issues/1046-- Subclassing Config has a few issues however:-- The Databricks SDK's attributes() method has bugs with subclassing:- 1. It only looks at cls.__dict__, not inherited attributes- 2. It caches results in _attributes, which subclasses inherit-- We work around this by copying parent ConfigAttribute descriptors into our __dict__.- """-- locals().update({k: v for k, v in Config.__dict__.items() if isinstance(v, ConfigAttribute)})-- @classmethod- def attributes(cls):- if "_attributes" not in cls.__dict__:- try:- delattr(cls, "_attributes")- except AttributeError:- pass- return super().attributes()-- @property- def oidc_endpoints(self) -> OidcEndpoints | None:- self._fix_host_if_needed()- if not self.host:- return None- if self.is_azure and self.azure_client_id:- return get_azure_entra_id_workspace_endpoints(self.host)- if self.is_account_client and self.account_id:- return get_account_endpoints(self.host, self.account_id)- return get_workspace_endpoints(self.host, client=_BaseClient(retry_timeout_seconds=5))--class DatabricksClient:# How often to poll for query status. This is a trade-off between responsiveness and number of# queries we make to Databricks. 1 second has been chosen rather arbitrarily.@@ -234,6 +193,7 @@ class DatabricksClient:client_secret: str,catalog: str,schema: str,+ statement_timeout_seconds: float | None = None,):self.server_hostname = server_hostnameself.http_path = http_path@@ -241,6 +201,10 @@ class DatabricksClient:self.client_secret = client_secretself.catalog = catalogself.schema = schema+ # Server-side safety net (Databricks ``STATEMENT_TIMEOUT`` SQL Conf). We typically set this+ # to be longer than the client-side per-call timeouts so the client fires first and the+ # server only kicks in as a last resort.+ self.statement_timeout_seconds = statement_timeout_secondsself._connection: None | Connection = None@@ -248,7 +212,12 @@ class DatabricksClient:self.external_logger = EXTERNAL_LOGGER.bind(server_hostname=server_hostname, http_path=http_path)@classmethod- def from_inputs_and_integration(cls, inputs: DatabricksInsertInputs, integration: DatabricksIntegration) -> t.Self:+ def from_inputs_and_integration(+ cls,+ inputs: DatabricksInsertInputs,+ integration: DatabricksIntegration,+ statement_timeout_seconds: float | None = None,+ ) -> t.Self:"""Initialize a DatabricksClient from `DatabricksInsertInputs` and `DatabricksIntegration`.The config for Databricks is divided between the inputs and the integration model:@@ -262,6 +231,7 @@ class DatabricksClient:client_secret=integration.client_secret,catalog=inputs.catalog,schema=inputs.schema,+ statement_timeout_seconds=statement_timeout_seconds,)@property@@ -274,10 +244,17 @@ class DatabricksClient:return self._connectionasync def _connect(self):- """Establish a raw Databricks connection in a separate thread."""+ """Establish a raw Databricks connection in a separate thread.++ Known hang risk: ``oauth_service_principal(config)`` triggers an OIDC endpoint discovery+ HTTP call inside ``sql.connect``. That call uses the Databricks SDK's own client timeout+ (~5 minutes, not configurable here), and doesn't respect the ``_socket_timeout`` / ``_retry_stop_after_*``+ settings. So if the host is unreachable or DNS hangs, this method can block for+ up to ~5 minutes before raising. See https://github.com/databricks/databricks-sdk-py/issues/1046.+ """def get_credential_provider():- config = DatabricksConfig(+ config = Config(host=f"https://{self.server_hostname}",client_id=self.client_id,client_secret=self.client_secret,@@ -295,9 +272,17 @@ class DatabricksClient:# user agent can be used for usage trackinguser_agent_entry="PostHog batch exports",enable_telemetry=False,- _socket_timeout=300, # Databricks seems to use this for all timeouts+ # Per-RPC, not per-query — long queries poll via repeated status RPCs.+ _socket_timeout=ONE_MINUTE,_retry_stop_after_attempts_count=2,- _retry_delay_max=1,+ # Cap the SDK's synchronous retry loop so a cancelled caller doesn't leave+ # the worker thread polling for ~15 minutes (the SDK's 900s default).+ _retry_stop_after_attempts_duration=ONE_MINUTE,+ session_configuration=(+ {"STATEMENT_TIMEOUT": str(int(self.statement_timeout_seconds))}+ if self.statement_timeout_seconds is not None+ else None+ ),)except TimeoutError:self.logger.info(@@ -344,6 +329,10 @@ class DatabricksClient:self._connection = await self._connect()self.logger.info("Connected to Databricks")+ # Verify the connection is responsive before proceeding+ await self.ping()+ self.logger.info("Ping successful")+if set_context is True:await self.use_catalog(self.catalog)await self.use_schema(self.schema)@@ -355,12 +344,29 @@ class DatabricksClient:await asyncio.to_thread(self._connection.close)self._connection = None+ async def _cancel_cursor(self, cursor: Cursor) -> None:+ """Issue a server-side CancelOperation so the worker thread running ``cursor.execute``+ unblocks (raising ``RequestError``) instead of spinning in the SDK's retry loop.+ """+ try:+ await asyncio.wait_for(asyncio.to_thread(cursor.cancel), timeout=10.0)+ except Exception as err:+ self.logger.warning("Failed to cancel Databricks cursor on cancellation: %s", err)+async def execute_query(- self, query: str, parameters: dict | None = None, query_kwargs: dict | None = None, fetch_results: bool = True+ self,+ query: str,+ parameters: dict | None = None,+ query_kwargs: dict | None = None,+ fetch_results: bool = True,+ timeout: float = ONE_HOUR,) -> list[Row] | None:"""Execute a query and wait for it to complete.We run the query in a separate thread to avoid blocking the event loop in the main thread.++ Use ``execute_async_query`` for long-running queries, where we poll for results rather than+ waiting for completion."""query_kwargs = query_kwargs or {}query_start_time = time.time()@@ -368,24 +374,31 @@ class DatabricksClient:with self.connection.cursor() as cursor:try:- await asyncio.to_thread(cursor.execute, query, parameters, **query_kwargs)+ async with asyncio.timeout(timeout):+ await asyncio.to_thread(cursor.execute, query, parameters, **query_kwargs)++ if not fetch_results:+ return None++ return await asyncio.to_thread(cursor.fetchall)+ except (asyncio.CancelledError, TimeoutError):+ # Abort server-side so that:+ # a) the user's warehouse doesn't keep running work nobody's waiting for+ # b) we cancel the running thread (otherwise, we could potentially run into+ # threadpool exhaustion)+ await self._cancel_cursor(cursor)+ raisefinally:query_execution_time = time.time() - query_start_timeself.logger.debug("Query completed in %.2fs", query_execution_time)- if not fetch_results:- return None-- results = await asyncio.to_thread(cursor.fetchall)- return results-async def execute_async_query(self,query: str,parameters: dict | None = None,poll_interval: float | None = None,fetch_results: bool = True,- timeout: float = 60 * 60, # 1 hour+ timeout: float = ONE_HOUR,) -> list[Row] | None:"""Execute a query asynchronously and poll for results.@@ -413,53 +426,73 @@ class DatabricksClient:self.logger.debug("Executing async query: %s", query)with self.connection.cursor() as cursor:- await asyncio.to_thread(cursor.execute_async, query, parameters)+ try:+ await asyncio.to_thread(cursor.execute_async, query, parameters)- self.logger.debug("Waiting for async query to complete")+ self.logger.debug("Waiting for async query to complete")- while await asyncio.to_thread(cursor.is_query_pending):- await asyncio.sleep(poll_interval)- if time.time() - query_start_time > timeout:- raise TimeoutError(f"Timed out waiting for query to complete after {timeout} seconds")+ while await asyncio.to_thread(cursor.is_query_pending):+ await asyncio.sleep(poll_interval)+ if time.time() - query_start_time > timeout:+ raise TimeoutError(f"Timed out waiting for query to complete after {timeout} seconds")- # this should return an exception if the query failed so ensure we log the query time- try:- await asyncio.to_thread(cursor.get_async_execution_result)- finally:- query_execution_time = time.time() - query_start_time- self.logger.debug("Async query completed in %.2fs", query_execution_time)+ # this should return an exception if the query failed so ensure we log the query time+ try:+ await asyncio.to_thread(cursor.get_async_execution_result)+ finally:+ query_execution_time = time.time() - query_start_time+ self.logger.debug("Async query completed in %.2fs", query_execution_time)- if fetch_results is False:- return None+ if fetch_results is False:+ return None++ self.logger.debug("Fetching query results")+ results = await asyncio.to_thread(cursor.fetchall)+ self.logger.debug("Finished fetching query results")++ return results+ except (asyncio.CancelledError, TimeoutError):+ # Abort server-side so that:+ # a) the user's warehouse doesn't keep running work nobody's waiting for+ # b) we cancel the running thread (otherwise, we could potentially run into+ # threadpool exhaustion)+ await self._cancel_cursor(cursor)+ raise- self.logger.debug("Fetching query results")- results = await asyncio.to_thread(cursor.fetchall)- self.logger.debug("Finished fetching query results")+ async def ping(self, timeout: float = FIVE_MINUTES) -> None:+ """Check that the Databricks warehouse is responsive.- return results+ If this basic query takes too long then it's a sign that the warehouse+ is either taking too long to resume or is under heavy load.+ """+ async with handle_common_errors("PING (SELECT 1)", timeout):+ await self.execute_query("SELECT 1", timeout=timeout)async def use_catalog(self, catalog: str):- try:- await self.execute_query(f"USE CATALOG `{catalog}`", fetch_results=False)- except ServerOperationError as err:- if err.message and "[NO_SUCH_CATALOG_EXCEPTION]" in err.message:- raise DatabricksCatalogNotFoundError(catalog)- elif _is_warehouse_stopped_error(err):- raise DatabricksWarehouseStoppedError("USE CATALOG", err.message)- raise+ timeout = ONE_MINUTE+ async with handle_common_errors(f"USE CATALOG {catalog}", timeout):+ try:+ await self.execute_query(f"USE CATALOG `{catalog}`", fetch_results=False, timeout=timeout)+ except ServerOperationError as err:+ if err.message and "[NO_SUCH_CATALOG_EXCEPTION]" in err.message:+ raise DatabricksCatalogNotFoundError(catalog)+ raiseasync def use_schema(self, schema: str):- try:- await self.execute_query(f"USE SCHEMA `{schema}`", fetch_results=False)- except ServerOperationError as err:- if err.message and "[SCHEMA_NOT_FOUND]" in err.message:- raise DatabricksSchemaNotFoundError(schema)- elif _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError(- "USE SCHEMA",- f"PERMISSION_DENIED: User does not have USE SCHEMA on Schema {schema}",- )- raise+ timeout = ONE_MINUTE+ async with handle_common_errors(f"USE SCHEMA {schema}", timeout):+ try:+ await self.execute_query(f"USE SCHEMA `{schema}`", fetch_results=False, timeout=timeout)+ except ServerOperationError as err:+ if err.message and "[SCHEMA_NOT_FOUND]" in err.message:+ raise DatabricksSchemaNotFoundError(schema)+ if _is_insufficient_permissions_error(err):+ # Use a more descriptive message than the raw err.message+ raise DatabricksInsufficientPermissionsError(+ "USE SCHEMA",+ f"PERMISSION_DENIED: User does not have USE SCHEMA on Schema {schema}",+ )+ raise@contextlib.asynccontextmanagerasync def managed_table(@@ -493,41 +526,33 @@ class DatabricksClient:async def acreate_table(self, table_name: str, fields: list[DatabricksField]):"""Asynchronously create the Databricks delta table if it doesn't exist."""+ timeout = FIVE_MINUTESfield_ddl = ", ".join(f"`{field[0]}` {field[1]}" for field in fields)- try:- query = f"""- CREATE TABLE IF NOT EXISTS `{table_name}` (- {field_ddl}- )- USING DELTA- COMMENT 'PostHog generated table'- """- await self.execute_query(query, fetch_results=False)- except ServerOperationError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError("CREATE TABLE", err.message)- raise+ query = f"""+ CREATE TABLE IF NOT EXISTS `{table_name}` (+ {field_ddl}+ )+ USING DELTA+ COMMENT 'PostHog generated table'+ """+ async with handle_common_errors(f"CREATE TABLE {table_name}", timeout):+ await self.execute_query(query, fetch_results=False, timeout=timeout)async def adelete_table(self, table_name: str):"""Asynchronously delete the Databricks delta table if it exists."""- try:- await self.execute_query(f"DROP TABLE IF EXISTS `{table_name}`", fetch_results=False)- except ServerOperationError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError("DROP TABLE", err.message)- raise+ timeout = FIVE_MINUTES+ async with handle_common_errors(f"DROP TABLE {table_name}", timeout):+ await self.execute_query(f"DROP TABLE IF EXISTS `{table_name}`", fetch_results=False, timeout=timeout)async def aput_file_stream_to_volume(self, file: io.BytesIO, volume_path: str, file_name: str):"""Asynchronously put a local file stream to a Databricks volume."""- try:+ timeout = ONE_HOUR+ async with handle_common_errors(f"PUT INTO '{volume_path}/{file_name}'", timeout):await self.execute_query(f"PUT '__input_stream__' INTO '{volume_path}/{file_name}' OVERWRITE",query_kwargs={"input_stream": file},+ timeout=timeout,)- except OperationalError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError(f"PUT INTO '{volume_path}/{file_name}'", err.message)- raiseasync def acopy_into_table_from_volume(self,@@ -535,21 +560,15 @@ class DatabricksClient:volume_path: str,fields: list[DatabricksField],with_schema_evolution: bool = True,- timeout: float = 60 * 60,+ timeout: float = ONE_HOUR,) -> None:"""Asynchronously copy data from a Databricks volume into a Databricks table."""self.logger.info("Copying data from volume into table '%s'", table_name)query = self._get_copy_into_table_from_volume_query(table_name=table_name, volume_path=volume_path, fields=fields, with_schema_evolution=with_schema_evolution)- try:+ async with handle_common_errors(f"COPY INTO {table_name} FROM VOLUME", timeout):await self.execute_async_query(query, fetch_results=False, timeout=timeout)- except TimeoutError:- raise DatabricksOperationTimeoutError(operation=f"COPY INTO {table_name} FROM VOLUME", timeout=timeout)- except ServerOperationError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError(f"COPY INTO {table_name} FROM VOLUME", err.message)- raisedef _get_copy_into_table_from_volume_query(self, table_name: str, volume_path: str, fields: list[DatabricksField], with_schema_evolution: bool = True@@ -609,44 +628,48 @@ class DatabricksClient:async def acreate_volume(self, volume: str):"""Asynchronously create a Databricks volume."""- try:+ timeout = FIVE_MINUTES+ async with handle_common_errors(f"CREATE VOLUME {volume}", timeout):await self.execute_query(f"CREATE VOLUME IF NOT EXISTS `{volume}` COMMENT 'PostHog generated volume'",fetch_results=False,+ timeout=timeout,)- except ServerOperationError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError("CREATE VOLUME", err.message)- raiseasync def adelete_volume(self, volume: str):"""Asynchronously delete a Databricks volume."""- try:+ timeout = FIVE_MINUTES+ async with handle_common_errors(f"DROP VOLUME {volume}", timeout):await self.execute_query(f"DROP VOLUME IF EXISTS `{volume}`",fetch_results=False,+ timeout=timeout,)- except ServerOperationError as err:- if _is_insufficient_permissions_error(err):- raise DatabricksInsufficientPermissionsError("DELETE VOLUME", err.message)- raise- async def aget_table_columns(self, table_name: str) -> list[str]:+ async def aget_table_columns(self, table_name: str, timeout: float = FIVE_MINUTES) -> list[str]:"""Asynchronously get the columns of a Databricks table.The Databricks connector has dedicated methods for retrieving metadata."""with self.connection.cursor() as cursor:try:- await asyncio.to_thread(- cursor.columns, catalog_name=self.catalog, schema_name=self.schema, table_name=table_name- )- results = await asyncio.to_thread(cursor.fetchall)- try:- column_names = [row.name for row in results]- except AttributeError:- # depending on the table column mapping mode, this could also be returned via a different attribute- column_names = [row.COLUMN_NAME for row in results]+ async with asyncio.timeout(timeout):+ await asyncio.to_thread(+ cursor.columns, catalog_name=self.catalog, schema_name=self.schema, table_name=table_name+ )+ results = await asyncio.to_thread(cursor.fetchall)+ try:+ column_names = [row.name for row in results]+ except AttributeError:+ # depending on the table column mapping mode, this could also be returned via a different attribute+ column_names = [row.COLUMN_NAME for row in results]+ except (asyncio.CancelledError, TimeoutError):+ # Abort server-side so that:+ # a) the user's warehouse doesn't keep running work nobody's waiting for+ # b) we cancel the running thread (otherwise, we could potentially run into+ # threadpool exhaustion)+ await self._cancel_cursor(cursor)+ raiseexcept DatabaseError as err:if "Expected field named: DataAccessConfigID" in str(err):raise DatabricksInsufficientPermissionsError(@@ -663,7 +686,7 @@ class DatabricksClient:update_key: collections.abc.Iterable[str],source_table_fields: collections.abc.Iterable[DatabricksField],with_schema_evolution: bool = True,- timeout: float = 60 * 60,+ timeout: float = ONE_HOUR,) -> None:"""Merge data from source_table into target_table in Databricks.@@ -706,16 +729,8 @@ class DatabricksClient:)try:- await self.execute_async_query(merge_query, fetch_results=False, timeout=timeout)- except TimeoutError:- self.logger.exception(- "Merge timed-out",- with_schema_evolution=with_schema_evolution,- query="MERGE",- query_details=merge_query,- timeout=timeout,- )- raise DatabricksOperationTimeoutError(operation="Merge into target table", timeout=timeout)+ async with handle_common_errors("Merge into target table", timeout):+ await self.execute_async_query(merge_query, fetch_results=False, timeout=timeout)except Exception:self.logger.exception("Merge failed", with_schema_evolution=with_schema_evolution, query="MERGE", query_details=merge_query@@ -946,11 +961,35 @@ def _is_insufficient_permissions_error(err: DatabaseError) -> bool:)-def _is_warehouse_stopped_error(err: ServerOperationError) -> bool:- """Check if the error is a warehouse stopped error."""- if err.message is None:- return False- return "warehouse" in err.message and "stopped" in err.message+async def handle_common_errors(operation: str, timeout: float) -> AsyncGenerator[None, None]:+ """Map common Databricks client errors to non-retryable typed exceptions.++ Operation-specific exceptions (catalog-not-found, schema-not-found, etc.) should be+ raised by a nested ``except`` inside this context manager — anything not remapped by+ that inner handler falls through here for the common treatment.+ """+ try:+ yield+ except TimeoutError:+ raise DatabricksOperationTimeoutError(operation=operation, timeout=timeout)+ except ServerOperationError as err:+ message = err.message or ""+ message_lower = message.lower()+ # Databricks currently returns "Statement has timed out after N seconds." but we+ # also match the SQLSTATE keyword "STATEMENT_TIMEOUT" in case the wording changes.+ if "statement_timeout" in message_lower or "statement has timed out" in message_lower:+ raise DatabricksOperationTimeoutError(operation=operation, timeout=timeout)+ if "warehouse" in message_lower and "stopped" in message_lower:+ raise DatabricksWarehouseStoppedError(operation, message)+ if _is_insufficient_permissions_error(err):+ raise DatabricksInsufficientPermissionsError(operation, message)+ raise+ except OperationalError as err:+ # PUT raises OperationalError on permission failures rather than ServerOperationError.+ if _is_insufficient_permissions_error(err):+ raise DatabricksInsufficientPermissionsError(operation, err.message or "")+ raisedef _get_long_running_query_timeout(data_interval_start: dt.datetime | None, data_interval_end: dt.datetime) -> float:@@ -962,8 +1001,8 @@ def _get_long_running_query_timeout(data_interval_start: dt.datetime | None, datWe can probably reduce this timeout a bit once the beta testing phase is complete."""- min_timeout_seconds = 30 * 60 # 30 minutes- max_timeout_seconds = 6 * 60 * 60 # 6 hours+ min_timeout_seconds = THIRTY_MINUTES+ max_timeout_seconds = SIX_HOURSif data_interval_start is None:return max_timeout_secondsinterval_seconds = (data_interval_end - data_interval_start).total_seconds()@@ -1138,7 +1177,12 @@ async def insert_into_databricks_activity_from_stage(inputs: DatabricksInsertInp)async with DatabricksClient.from_inputs_and_integration(- inputs, databricks_integration+ inputs,+ databricks_integration,+ # Server-side STATEMENT_TIMEOUT is a backstop just to ensure the+ # query doesn't hang indefinitely (we should always time out on the+ # client before it reaches this point)+ statement_timeout_seconds=long_running_query_timeout + ONE_MINUTE,).connect() as databricks_client:async with manage_resources(client=databricks_client,diff --git a/products/batch_exports/backend/tests/temporal/destinations/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/conftest.pyindex 370487fca3c2..e11e745ca621 100644--- a/products/batch_exports/backend/tests/temporal/destinations/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/conftest.py@@ -1,3 +1,5 @@+import pytest+import pytest_asynciofrom products.batch_exports.backend.tests.temporal.utils.clickhouse import (@@ -8,6 +10,16 @@ from products.batch_exports.backend.tests.temporal.utils.clickhouse import ()+# Since we autouse the `clickhouse_db_setup` below we need every test in this+# directory to have DB access, otherwise we can run into some strange errors+# during test setup. Requesting pytest-django's `db` fixture from an autouse+# fixture grants that access, and because this conftest is directory-scoped it+# only applies to tests under this directory.[email protected](autouse=True)+def _enable_db(db):+ pass++@pytest_asyncio.fixture(scope="module", autouse=True, loop_scope="module")async def clickhouse_db_setup(clickhouse_client, django_db_setup):await create_clickhouse_tables_and_views(clickhouse_client)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.pyindex 8c2661fe6f80..e56ec00e5073 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,15 +1,37 @@+import os+import time+import asyncio+import threading+import pytest-import unittest.mock+from unittest.mock import AsyncMock, MagicMock, patch++from databricks.sql.exc import RequestError, ServerOperationErrorfrom products.batch_exports.backend.temporal.destinations.databricks_batch_export import (DatabricksClient,DatabricksConnectionError,+ DatabricksOperationTimeoutError,)+# Env vars required for the real-connection tests below. The _BE suffix avoids conflicts+# with env vars the Databricks SDK auto-discovers.+REAL_DATABRICKS_ENV_VARS = (+ "DATABRICKS_BE_SERVER_HOSTNAME",+ "DATABRICKS_BE_HTTP_PATH",+ "DATABRICKS_BE_CLIENT_ID",+ "DATABRICKS_BE_CLIENT_SECRET",+)-async def test_get_merge_query_with_schema_evolution():- """Test that we construct the correct SQL for merging with schema evolution."""- client = DatabricksClient(+skip_without_real_databricks = pytest.mark.skipif(+ not all(env_var in os.environ for env_var in REAL_DATABRICKS_ENV_VARS),+ reason=f"Databricks required env vars are not set: {', '.join(REAL_DATABRICKS_ENV_VARS)}",+)+++def client() -> DatabricksClient:+ return DatabricksClient(server_hostname="test",http_path="test",client_id="test",@@ -17,17 +39,129 @@ async def test_get_merge_query_with_schema_evolution():catalog="test",schema="test",)- merge_key = ["team_id", "distinct_id"]- update_key = ["person_version", "person_distinct_id_version"]- merge_query = client._get_merge_query_with_schema_evolution(- target_table="test_target",- source_table="test_source",- merge_key=merge_key,- update_key=update_key,- )- assert (- merge_query- == """+++def mock_cursor(client: DatabricksClient) -> MagicMock:+ cursor = MagicMock()+ cursor.__enter__ = MagicMock(return_value=cursor)+ cursor.__exit__ = MagicMock(return_value=False)+ connection = MagicMock()+ connection.cursor.return_value = cursor+ client._connection = connection+ return cursor+++class TestExecuteQuery:+ @pytest.mark.parametrize("trigger", ["cancellation", "timeout"])+ async def test_cancels_cursor_on_cancellation_or_timeout(+ self, client: DatabricksClient, mock_cursor: MagicMock, trigger: str+ ):+ """Both task cancellation and per-call timeout should issue ``cursor.cancel()`` so the blocked+ worker thread running ``cursor.execute`` releases."""+ started_event = threading.Event()+ release_event = threading.Event()++ def blocking_execute(*_args, **_kwargs):+ started_event.set()+ release_event.wait(timeout=30)+ # Mirrors upstream SDK behavior: after cancel() is called, execute() raises RequestError.+ raise RequestError("query was cancelled")++ mock_cursor.execute.side_effect = blocking_execute+ mock_cursor.cancel.side_effect = lambda *_a, **_kw: release_event.set()++ if trigger == "cancellation":+ execute_task = asyncio.create_task(client.execute_query("SELECT 1", fetch_results=False))+ await asyncio.to_thread(started_event.wait, 5)+ execute_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await execute_task+ else:+ with pytest.raises(TimeoutError):+ await client.execute_query("SELECT 1", fetch_results=False, timeout=0.1)++ mock_cursor.cancel.assert_called_once()+ assert release_event.is_set()++ async def test_does_not_call_cancel_on_normal_completion(self, client: DatabricksClient, mock_cursor: MagicMock):+ """A successful query should not trigger a server-side cursor cancel."""+ mock_cursor.fetchall.return_value = []++ result = await client.execute_query("SELECT 1")++ assert result == []+ mock_cursor.execute.assert_called_once()+ mock_cursor.cancel.assert_not_called()++ async def test_propagates_genuine_request_error(self, client: DatabricksClient, mock_cursor: MagicMock):+ """A ``RequestError`` raised by ``cursor.execute`` (not from a cancel) should propagate+ unchanged, and we should not issue a redundant ``cursor.cancel()``."""+ mock_cursor.execute.side_effect = RequestError("transient failure")++ with pytest.raises(RequestError, match="transient failure"):+ await client.execute_query("SELECT 1", fetch_results=False)++ mock_cursor.cancel.assert_not_called()++ async def test_async_query_cancels_cursor_on_internal_timeout(+ self, client: DatabricksClient, mock_cursor: MagicMock+ ):+ """``execute_async_query``'s poll-loop timeout should also issue a ``cursor.cancel()``."""+ mock_cursor.is_query_pending.return_value = True++ with pytest.raises(TimeoutError, match="Timed out waiting for query"):+ await client.execute_async_query("SELECT 1", fetch_results=False, poll_interval=0.01, timeout=0.05)++ mock_cursor.cancel.assert_called_once()+++class TestConnect:+ async def test_when_ping_times_out(self, client: DatabricksClient):+ """If the warehouse is asleep and doesn't resume within the ping timeout, ``connect()`` should+ raise ``DatabricksOperationTimeoutError`` before attempting ``use_catalog``."""+ use_catalog_mock = AsyncMock()++ with (+ patch(+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",+ return_value=MagicMock(),+ ),+ patch.object(client, "execute_query", side_effect=TimeoutError("timed out")),+ patch.object(client, "use_catalog", new=use_catalog_mock),+ ):+ with pytest.raises(DatabricksOperationTimeoutError):+ async with client.connect():+ pass++ use_catalog_mock.assert_not_called()++ async def test_when_invalid_host(self, client: DatabricksClient):+ with patch(+ "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",+ side_effect=ValueError("invalid host"),+ ):+ with pytest.raises(+ DatabricksConnectionError,+ match="Failed to connect to Databricks. Please check that your connection details are valid.",+ ):+ async with client.connect():+ pass+++class TestQueryBuilders:+ async def test_merge_query_with_schema_evolution(self, client: DatabricksClient):+ merge_key = ["team_id", "distinct_id"]+ update_key = ["person_version", "person_distinct_id_version"]+ merge_query = client._get_merge_query_with_schema_evolution(+ target_table="test_target",+ source_table="test_source",+ merge_key=merge_key,+ update_key=update_key,+ )+ assert (+ merge_query+ == """MERGE WITH SCHEMA EVOLUTION INTO `test_target` AS targetUSING `test_source` AS sourceON target.`team_id` = source.`team_id` AND target.`distinct_id` = source.`distinct_id`@@ -36,44 +170,34 @@ async def test_get_merge_query_with_schema_evolution():WHEN NOT MATCHED THENINSERT *"""- )-+ )-async def test_get_merge_query_without_schema_evolution():- """Test that we construct the correct SQL for merging without schema evolution."""- client = DatabricksClient(- server_hostname="test",- http_path="test",- client_id="test",- client_secret="test",- catalog="test",- schema="test",- )- merge_key = ["team_id", "distinct_id"]- update_key = ["person_version", "person_distinct_id_version"]- merge_query = client._get_merge_query_without_schema_evolution(- target_table="test_target",- source_table="test_source",- merge_key=merge_key,- update_key=update_key,- source_table_fields=[- ("team_id", "INTEGER"),- ("distinct_id", "STRING"),- ("person_version", "INTEGER"),- ("person_distinct_id_version", "INTEGER"),- ("properties", "VARIANT"),- ],- target_table_field_names=[- "team_id",- "distinct_id",- "person_version",- "person_distinct_id_version",- "properties",- ],- )- assert (- merge_query- == """+ async def test_merge_query_without_schema_evolution(self, client: DatabricksClient):+ merge_key = ["team_id", "distinct_id"]+ update_key = ["person_version", "person_distinct_id_version"]+ merge_query = client._get_merge_query_without_schema_evolution(+ target_table="test_target",+ source_table="test_source",+ merge_key=merge_key,+ update_key=update_key,+ source_table_fields=[+ ("team_id", "INTEGER"),+ ("distinct_id", "STRING"),+ ("person_version", "INTEGER"),+ ("person_distinct_id_version", "INTEGER"),+ ("properties", "VARIANT"),+ ],+ target_table_field_names=[+ "team_id",+ "distinct_id",+ "person_version",+ "person_distinct_id_version",+ "properties",+ ],+ )+ assert (+ merge_query+ == """MERGE INTO `test_target` AS targetUSING `test_source` AS sourceON target.`team_id` = source.`team_id` AND target.`distinct_id` = source.`distinct_id`@@ -84,49 +208,42 @@ async def test_get_merge_query_without_schema_evolution():INSERT (`team_id`, `distinct_id`, `person_version`, `person_distinct_id_version`, `properties`)VALUES (source.`team_id`, source.`distinct_id`, source.`person_version`, source.`person_distinct_id_version`, source.`properties`)"""- )-+ )-async def test_get_merge_query_without_schema_evolution_and_target_table_has_less_fields():- """Test that we construct the correct SQL for merging without schema evolution and the target table has less- fields.+ async def test_merge_query_without_schema_evolution_and_target_table_has_less_fields(+ self, client: DatabricksClient+ ):+ """Test that we construct the correct SQL for merging without schema evolution and the target table has less+ fields.- In this example, the "new_field" field should be ignored.- """- client = DatabricksClient(- server_hostname="test",- http_path="test",- client_id="test",- client_secret="test",- catalog="test",- schema="test",- )- merge_key = ["team_id", "distinct_id"]- update_key = ["person_version", "person_distinct_id_version"]- merge_query = client._get_merge_query_without_schema_evolution(- target_table="test_target",- source_table="test_source",- merge_key=merge_key,- update_key=update_key,- source_table_fields=[- ("team_id", "INTEGER"),- ("distinct_id", "STRING"),- ("person_version", "INTEGER"),- ("person_distinct_id_version", "INTEGER"),- ("properties", "VARIANT"),- ("new_field", "STRING"),- ],- target_table_field_names=[- "team_id",- "distinct_id",- "person_version",- "person_distinct_id_version",- "properties",- ],- )- assert (- merge_query- == """+ In this example, the "new_field" field should be ignored.+ """+ merge_key = ["team_id", "distinct_id"]+ update_key = ["person_version", "person_distinct_id_version"]+ merge_query = client._get_merge_query_without_schema_evolution(+ target_table="test_target",+ source_table="test_source",+ merge_key=merge_key,+ update_key=update_key,+ source_table_fields=[+ ("team_id", "INTEGER"),+ ("distinct_id", "STRING"),+ ("person_version", "INTEGER"),+ ("person_distinct_id_version", "INTEGER"),+ ("properties", "VARIANT"),+ ("new_field", "STRING"),+ ],+ target_table_field_names=[+ "team_id",+ "distinct_id",+ "person_version",+ "person_distinct_id_version",+ "properties",+ ],+ )+ assert (+ merge_query+ == """MERGE INTO `test_target` AS targetUSING `test_source` AS sourceON target.`team_id` = source.`team_id` AND target.`distinct_id` = source.`distinct_id`@@ -137,35 +254,27 @@ async def test_get_merge_query_without_schema_evolution_and_target_table_has_lesINSERT (`team_id`, `distinct_id`, `person_version`, `person_distinct_id_version`, `properties`)VALUES (source.`team_id`, source.`distinct_id`, source.`person_version`, source.`person_distinct_id_version`, source.`properties`)"""- )-+ )-async def test_get_copy_into_table_from_volume_query():- client = DatabricksClient(- server_hostname="test",- http_path="test",- client_id="test",- client_secret="test",- catalog="test",- schema="test",- )- fields = [- ("uuid", "STRING"),- ("event", "STRING"),- ("properties", "VARIANT"),- ("distinct_id", "STRING"),- ("team_id", "BIGINT"),- ("timestamp", "TIMESTAMP"),- ("databricks_ingested_timestamp", "TIMESTAMP"),- ]- query = client._get_copy_into_table_from_volume_query(- table_name="test_table",- volume_path="/Volumes/my_volume/path/file.parquet",- fields=fields,- )- assert (- query- == """+ async def test_copy_into_table_from_volume_query(self, client: DatabricksClient):+ """Test that we construct the correct SQL for COPY INTO from a volume, including VARIANT/BIGINT casts."""+ fields = [+ ("uuid", "STRING"),+ ("event", "STRING"),+ ("properties", "VARIANT"),+ ("distinct_id", "STRING"),+ ("team_id", "BIGINT"),+ ("timestamp", "TIMESTAMP"),+ ("databricks_ingested_timestamp", "TIMESTAMP"),+ ]+ query = client._get_copy_into_table_from_volume_query(+ table_name="test_table",+ volume_path="/Volumes/my_volume/path/file.parquet",+ fields=fields,+ )+ assert (+ query+ == """COPY INTO `test_table`FROM (SELECT `uuid`, `event`, PARSE_JSON(`properties`) as `properties`, `distinct_id`, CAST(`team_id` as BIGINT) as `team_id`, `timestamp`, `databricks_ingested_timestamp` FROM '/Volumes/my_volume/path/file.parquet'@@ -173,26 +282,62 @@ async def test_get_copy_into_table_from_volume_query():FILEFORMAT = PARQUETCOPY_OPTIONS ('force' = 'true', 'mergeSchema' = 'true')"""- )+ )-async def test_connect_when_invalid_host():- """Test that we raise an error when the host is invalid."""- client = DatabricksClient(- server_hostname="invalid",- http_path="test",- client_id="test",- client_secret="test",- catalog="test",- schema="test",+@skip_without_real_databricks+class TestRealDatabricksConnection:+ """Tests that exercise behavior against a real Databricks SQL warehouse.++ Skipped when ``DATABRICKS_BE_*`` env vars are missing.+ """++ # Databricks SQL doesn't have a native `sleep()` function, so we use an example from+ # https://github.com/databricks/databricks-sql-python/blob/cbd6a883f003f5f035db30705081208eb8af3de0/examples/query_cancel.py#L19-L21+ LONG_RUNNING_QUERY = (+ "SELECT SUM(A.id - B.id) FROM range(1000000000) A CROSS JOIN range(100000000) B GROUP BY (A.id - B.id)")- with unittest.mock.patch(- "products.batch_exports.backend.temporal.destinations.databricks_batch_export.sql.connect",- side_effect=ValueError("invalid host"),- ):- with pytest.raises(- DatabricksConnectionError,- match="Failed to connect to Databricks. Please check that your connection details are valid.",- ):- async with client.connect():- pass++ @staticmethod+ def _make_client(statement_timeout_seconds: float | None = None) -> DatabricksClient:+ return DatabricksClient(+ server_hostname=os.environ["DATABRICKS_BE_SERVER_HOSTNAME"],+ http_path=os.environ["DATABRICKS_BE_HTTP_PATH"],+ client_id=os.environ["DATABRICKS_BE_CLIENT_ID"],+ client_secret=os.environ["DATABRICKS_BE_CLIENT_SECRET"],+ catalog=os.getenv("DATABRICKS_CATALOG", "batch_export_tests"),+ schema="default",+ statement_timeout_seconds=statement_timeout_seconds,+ )++ async def test_execute_query_timeout_aborts_query_and_unblocks_worker_thread(self):+ """Tests that:+ 1. ``execute_query``'s timeout actually fires and raises ``TimeoutError``.+ 2. The worker thread running ``cursor.execute`` actually releases — this relies+ on databricks-sql-python's ``cursor.cancel()`` being called from another+ thread.+ See https://github.com/databricks/databricks-sql-python/blob/main/examples/query_cancel.py+ """+ client = self._make_client()++ started_at = time.monotonic()+ async with client.connect(set_context=False):+ with pytest.raises(TimeoutError):+ await client.execute_query(self.LONG_RUNNING_QUERY, fetch_results=False, timeout=1)+ elapsed = time.monotonic() - started_at++ # 1s timeout + cursor.cancel() RPC + thread teardown should land well under the SDK's+ # _retry_stop_after_attempts_duration ceiling. If we ever see this assertion fail it+ # almost certainly means cursor.cancel() didn't unblock the worker.+ assert elapsed < 30, f"execute_query took {elapsed:.1f}s after a 1s timeout — worker thread didn't release"++ async def test_server_side_statement_timeout_aborts_long_running_query(self):+ """+ Tests that setting ``statement_timeout_seconds`` works as expected, i.e.+ the server aborts queries exceeding the specified timeout.+ """+ client = self._make_client(statement_timeout_seconds=1)++ async with client.connect(set_context=False):+ with pytest.raises(ServerOperationError, match="Statement has timed out after 1 second"):+ await client.execute_query(self.LONG_RUNNING_QUERY, fetch_results=False)