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(data-warehouse): treat credential errors as configuration errors for snowflake, databricks, redshift and s3 (#115557)

Tom Owers6bf5443d0397
diff --git a/products/batch_exports/backend/facade/destinations/databricks.py b/products/batch_exports/backend/facade/destinations/databricks.py
index 1cc9f8f1b28e..1e071edea117 100644
--- a/products/batch_exports/backend/facade/destinations/databricks.py
+++ b/products/batch_exports/backend/facade/destinations/databricks.py
@@ -12,16 +12,30 @@ from products.batch_exports.backend.temporal.destinations.databricks_batch_expor
FIVE_MINUTES,
ONE_HOUR,
ONE_MINUTE,
+ DatabricksCatalogNotFoundError,
DatabricksClient,
+ DatabricksConnectionError,
DatabricksField,
+ DatabricksIncompatibleSchemaError,
+ DatabricksInsufficientPermissionsError,
DatabricksIntegrationNotFoundError,
+ DatabricksOperationTimeoutError,
+ DatabricksSchemaNotFoundError,
+ DatabricksWarehouseStoppedError,
handle_common_errors,
)
__all__ = [
+ "DatabricksCatalogNotFoundError",
"DatabricksClient",
+ "DatabricksConnectionError",
"DatabricksField",
+ "DatabricksIncompatibleSchemaError",
+ "DatabricksInsufficientPermissionsError",
"DatabricksIntegrationNotFoundError",
+ "DatabricksOperationTimeoutError",
+ "DatabricksSchemaNotFoundError",
+ "DatabricksWarehouseStoppedError",
"FIVE_MINUTES",
"ONE_HOUR",
"ONE_MINUTE",
diff --git a/products/batch_exports/backend/facade/destinations/redshift.py b/products/batch_exports/backend/facade/destinations/redshift.py
index 0012ae9c3fe7..63724c10e8e1 100644
--- a/products/batch_exports/backend/facade/destinations/redshift.py
+++ b/products/batch_exports/backend/facade/destinations/redshift.py
@@ -7,8 +7,12 @@ Importing this module loads the destination's vendor SDK, so keep it off the
``django.setup()`` path. See ``posthog/test/repo_invariants/test_startup_import_budget.py``.
"""
-from products.batch_exports.backend.temporal.destinations.redshift_batch_export import RedshiftClient
+from products.batch_exports.backend.temporal.destinations.redshift_batch_export import (
+ RedshiftClient,
+ StringLimitExceededError,
+)
__all__ = [
"RedshiftClient",
+ "StringLimitExceededError",
]
diff --git a/products/batch_exports/backend/facade/destinations/s3.py b/products/batch_exports/backend/facade/destinations/s3.py
index 6afd1479a482..e7d2896b8799 100644
--- a/products/batch_exports/backend/facade/destinations/s3.py
+++ b/products/batch_exports/backend/facade/destinations/s3.py
@@ -11,7 +11,9 @@ Importing this module loads the destination's vendor SDK, so keep it off the
from products.batch_exports.backend.temporal.destinations.constants import S3_SUPPORTED_COMPRESSIONS
from products.batch_exports.backend.temporal.destinations.s3_batch_export import (
ConcurrentS3Consumer,
+ ExternalRoleArnNotConfiguredError,
IntermittentUploadPartTimeoutError,
+ InvalidCredentialsError,
PolicyStatement,
S3IntegrationNotFoundError,
_get_s3_integration as get_s3_integration,
@@ -21,7 +23,9 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export import
__all__ = [
"ConcurrentS3Consumer",
+ "ExternalRoleArnNotConfiguredError",
"IntermittentUploadPartTimeoutError",
+ "InvalidCredentialsError",
"PolicyStatement",
"S3IntegrationNotFoundError",
"S3_SUPPORTED_COMPRESSIONS",
diff --git a/products/batch_exports/backend/facade/destinations/snowflake.py b/products/batch_exports/backend/facade/destinations/snowflake.py
index 075f49977c61..db5721e2c0a8 100644
--- a/products/batch_exports/backend/facade/destinations/snowflake.py
+++ b/products/batch_exports/backend/facade/destinations/snowflake.py
@@ -9,21 +9,45 @@ Importing this module loads the destination's vendor SDK, so keep it off the
"""
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (
+ InvalidPrivateKeyError,
NamedBytesIO,
+ SnowflakeAuthenticationError,
SnowflakeClient,
+ SnowflakeConnectionError,
SnowflakeField,
+ SnowflakeFileNotLoadedError,
+ SnowflakeIncompatibleSchemaError,
+ SnowflakeInsufficientPrivilegesError,
+ SnowflakeIntegrationNotFoundError,
+ SnowflakeQueryClientTimeoutError,
+ SnowflakeQueryServerTimeoutError,
+ SnowflakeRetryableConnectionError,
SnowflakeTable,
SnowflakeType,
+ SnowflakeWarehouseSuspendedError,
+ SnowflakeWarehouseUsageError,
_get_snowflake_integration as get_snowflake_integration,
load_private_key,
)
__all__ = [
+ "InvalidPrivateKeyError",
"NamedBytesIO",
+ "SnowflakeAuthenticationError",
"SnowflakeClient",
+ "SnowflakeConnectionError",
"SnowflakeField",
+ "SnowflakeFileNotLoadedError",
+ "SnowflakeIncompatibleSchemaError",
+ "SnowflakeInsufficientPrivilegesError",
+ "SnowflakeIntegrationNotFoundError",
+ "SnowflakeQueryClientTimeoutError",
+ "SnowflakeQueryServerTimeoutError",
+ "SnowflakeRetryableConnectionError",
"SnowflakeTable",
"SnowflakeType",
+ "SnowflakeWarehouseSuspendedError",
+ "SnowflakeWarehouseUsageError",
"get_snowflake_integration",
"load_private_key",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py
index c33235c81563..9b823a26f6a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py
@@ -1,18 +1,38 @@
from collections.abc import AsyncIterator
+from dataclasses import replace
import pytest
+from unittest import mock
import pyarrow as pa
+from databricks.sql.exc import ServerOperationError
from parameterized import parameterized
-from products.batch_exports.backend.facade.destinations.databricks import DatabricksClient
+from products.batch_exports.backend.facade.destinations.databricks import (
+ DatabricksCatalogNotFoundError,
+ DatabricksClient,
+ DatabricksConnectionError,
+ DatabricksIncompatibleSchemaError,
+ DatabricksInsufficientPermissionsError,
+ DatabricksIntegrationNotFoundError,
+ DatabricksOperationTimeoutError,
+ DatabricksSchemaNotFoundError,
+ DatabricksWarehouseStoppedError,
+)
from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ MISSING_INTEGRATION_DETAIL,
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_databricks import (
FakeDatabricksClient,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers import (
+ databricks,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.databricks import (
DatabricksDestinationWriter,
UnrelatedTableExistsError,
@@ -61,6 +81,97 @@ def _read(client: FakeDatabricksClient, table: str) -> list[tuple]:
return sorted((row["id"], row["name"]) for row in client.tables[table.lower()].rows)
+class TestConfigurationErrors:
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ ("error", "detail_word"),
+ [
+ (DatabricksConnectionError("fake-secret", retryable=False), "hostname"),
+ (DatabricksInsufficientPermissionsError("CREATE TABLE", "fake-secret"), "WRITE VOLUME"),
+ (DatabricksCatalogNotFoundError("fake-secret"), "catalog"),
+ (DatabricksSchemaNotFoundError("fake-secret"), "schema"),
+ (DatabricksIntegrationNotFoundError("fake-secret"), "connection details"),
+ ],
+ )
+ async def test_permanent_errors_are_configuration_errors(
+ self, error: Exception, detail_word: str, finalize: bool
+ ) -> None:
+ ctx = replace(_ctx("charges", "run-a1"), sync_type="full_refresh")
+ client = FakeDatabricksClient()
+ writer = LocalDatabricksWriter(ctx, client)
+ target = client if isinstance(error, DatabricksInsufficientPermissionsError) else writer
+ method = "aget_table_columns" if isinstance(error, DatabricksInsufficientPermissionsError) else "_make_client"
+
+ with (
+ mock.patch.object(target, method, side_effect=error),
+ pytest.raises(DestinationConfigurationError, match=detail_word) as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+ assert caught.value.__cause__ is error
+ assert str(error) not in caught.value.detail
+ assert "fake-secret" not in caught.value.detail
+
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ "error",
+ [
+ DatabricksConnectionError("fake-secret", retryable=True),
+ DatabricksConnectionError("fake-secret"),
+ DatabricksOperationTimeoutError("COPY INTO", 1),
+ DatabricksWarehouseStoppedError("COPY INTO", "fake-secret"),
+ DatabricksIncompatibleSchemaError("COPY INTO", "fake-secret"),
+ ServerOperationError("fake-secret"),
+ TimeoutError("fake-secret"),
+ UnrelatedTableExistsError("fake-secret"),
+ OSError("fake-secret"),
+ ],
+ )
+ async def test_transient_errors_propagate_unchanged(self, error: Exception, finalize: bool) -> None:
+ ctx = replace(_ctx("charges", "run-a1"), sync_type="full_refresh")
+ client = FakeDatabricksClient()
+ writer = LocalDatabricksWriter(ctx, client)
+
+ with (
+ mock.patch.object(client, "aget_table_columns", side_effect=error),
+ pytest.raises(type(error)) as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value is error
+ assert not isinstance(caught.value, DestinationConfigurationError)
+
+ @pytest.mark.parametrize("integration_id", [None, 42])
+ async def test_missing_connection_details_are_configuration_errors(self, integration_id: int | None) -> None:
+ ctx = replace(_ctx("charges", "run-a1"), integration_id=integration_id)
+ writer = DatabricksDestinationWriter(ctx)
+
+ with (
+ mock.patch.object(
+ databricks, "_load_integration", side_effect=DatabricksIntegrationNotFoundError("fake-secret")
+ ),
+ pytest.raises(DestinationConfigurationError, match="connection details") as caught,
+ ):
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value.detail == MISSING_INTEGRATION_DETAIL
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+ assert "fake-secret" not in caught.value.detail
+
+
class TestUnityCatalogNameCase:
"""Unity Catalog lowercases the names it stores, so a writer that looks its own table up
case-sensitively stops recognizing it as soon as the name carries any uppercase. The run
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_redshift_configuration_errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_redshift_configuration_errors.py
new file mode 100644
index 000000000000..28e675aa8983
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_redshift_configuration_errors.py
@@ -0,0 +1,124 @@
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+
+import pytest
+from unittest import mock
+
+import psycopg
+import pyarrow as pa
+
+from products.batch_exports.backend.facade.destinations.postgres import PostgreSQLClient
+from products.batch_exports.backend.facade.destinations.redshift import StringLimitExceededError
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ DestinationConfigurationError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import (
+ UnrelatedTableExistsError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.redshift import (
+ RedshiftDestinationWriter,
+)
+
+
+def _ctx() -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id="schema",
+ source_id="source",
+ job_id="job",
+ run_uuid="run-a1",
+ destination_id="destination",
+ destination_type="Redshift",
+ destination_name="test redshift",
+ table_name="charges",
+ sync_type="incremental",
+ config={"schema": "public"},
+ )
+
+
+async def _batches() -> AsyncIterator[pa.RecordBatch]:
+ yield pa.RecordBatch.from_pydict({"id": [1]})
+
+
+class LocalRedshiftWriter(RedshiftDestinationWriter):
+ def __init__(self, ctx: DestinationRunContext, client: PostgreSQLClient) -> None:
+ super().__init__(ctx)
+ self._fake = client
+
+ @asynccontextmanager
+ async def _client(self) -> AsyncIterator[PostgreSQLClient]:
+ yield self._fake
+
+
+class TestConfigurationErrors:
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ "error",
+ [
+ psycopg.errors.InsufficientPrivilege("permission denied for schema fake-secret"),
+ psycopg.errors.InsufficientPrivilege("permission denied for table fake-secret"),
+ ],
+ )
+ async def test_permanent_errors_are_configuration_errors(self, error: Exception, finalize: bool) -> None:
+ ctx = _ctx()
+ client = mock.AsyncMock(spec=PostgreSQLClient)
+ writer = LocalRedshiftWriter(ctx, client)
+ client.adelete_table.side_effect = error
+
+ with (
+ mock.patch.object(writer, "_table_exists", return_value=False),
+ mock.patch.object(writer, "_ensure_table", side_effect=error),
+ pytest.raises(DestinationConfigurationError, match="USAGE and CREATE") as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+ assert caught.value.__cause__ is error
+ assert str(error) not in caught.value.detail
+ assert "fake-secret" not in caught.value.detail
+
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ "error",
+ [
+ psycopg.OperationalError("fake-secret"),
+ psycopg.errors.SerializationFailure("fake-secret"),
+ psycopg.errors.DeadlockDetected("fake-secret"),
+ psycopg.errors.QueryCanceled("fake-secret"),
+ psycopg.errors.ConnectionTimeout("fake-secret"),
+ psycopg.errors.AdminShutdown("fake-secret"),
+ StringLimitExceededError("fake-secret", "charges", "public"),
+ UnrelatedTableExistsError("fake-secret"),
+ TimeoutError("fake-secret"),
+ ],
+ )
+ async def test_transient_errors_propagate_unchanged(self, error: Exception, finalize: bool) -> None:
+ ctx = _ctx()
+ client = mock.AsyncMock(spec=PostgreSQLClient)
+ writer = LocalRedshiftWriter(ctx, client)
+ client.adelete_table.side_effect = error
+
+ with (
+ mock.patch.object(writer, "_table_exists", return_value=False),
+ mock.patch.object(writer, "_ensure_table", side_effect=error),
+ pytest.raises(type(error)) as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value is error
+ assert not isinstance(caught.value, DestinationConfigurationError)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_s3_configuration_errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_s3_configuration_errors.py
new file mode 100644
index 000000000000..d50d1234215c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_s3_configuration_errors.py
@@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from typing import TYPE_CHECKING, Any
+
+import pytest
+from unittest import mock
+
+import pyarrow as pa
+import botocore.exceptions
+
+from products.batch_exports.backend.facade.destinations.s3 import (
+ ExternalRoleArnNotConfiguredError,
+ IntermittentUploadPartTimeoutError,
+ InvalidCredentialsError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ DestinationConfigurationError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.s3 import (
+ S3DestinationWriter,
+)
+
+if TYPE_CHECKING:
+ from types_aiobotocore_s3.client import S3Client
+
+
+def _ctx() -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id="schema",
+ source_id="source",
+ job_id="job",
+ run_uuid="run-a1",
+ destination_id="destination",
+ destination_type="S3",
+ destination_name="test s3",
+ table_name="charges",
+ sync_type="full_refresh",
+ integration_id=42,
+ config={"bucket": "example-bucket", "region": "us-east-1"},
+ )
+
+
+def _client_error(code: str, operation: str = "PutObject", status: int = 403) -> botocore.exceptions.ClientError:
+ response: Any = {"Error": {"Code": code, "Message": "fake-secret"}, "ResponseMetadata": {"HTTPStatusCode": status}}
+ return botocore.exceptions.ClientError(response, operation)
+
+
+async def _batches() -> AsyncIterator[pa.RecordBatch]:
+ yield pa.RecordBatch.from_pydict({"id": [1]})
+
+
+class LocalS3Writer(S3DestinationWriter):
+ def __init__(self, ctx: DestinationRunContext, client: S3Client, connection_error: Exception | None) -> None:
+ super().__init__(ctx)
+ self._fake = client
+ self._connection_error = connection_error
+
+ @asynccontextmanager
+ async def _client(self) -> AsyncIterator[S3Client]:
+ if self._connection_error is not None:
+ raise self._connection_error
+ yield self._fake
+
+
+class TestConfigurationErrors:
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ ("error", "detail_word", "at_connect"),
+ [
+ (_client_error("InvalidAccessKeyId"), "access key ID", False),
+ (_client_error("SignatureDoesNotMatch"), "access key ID", False),
+ (_client_error("NoSuchBucket"), "bucket name and region", False),
+ (_client_error("AccessDenied"), "s3:PutObject", False),
+ (_client_error("AccessDeniedException"), "s3:AbortMultipartUpload", False),
+ (_client_error("AccessDenied", "AssumeRole"), "trust policy", True),
+ (_client_error("AccessDeniedException", "AssumeRole"), "external ID", True),
+ (InvalidCredentialsError("fake-secret"), "trust policy", True),
+ ],
+ )
+ async def test_permanent_errors_are_configuration_errors(
+ self, error: Exception, detail_word: str, at_connect: bool, finalize: bool
+ ) -> None:
+ ctx = _ctx()
+ client = mock.AsyncMock()
+ client.put_object.side_effect = error
+ writer = LocalS3Writer(ctx, client, error if at_connect else None)
+
+ with pytest.raises(DestinationConfigurationError, match=detail_word) as caught:
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+ assert caught.value.__cause__ is error
+ assert str(error) not in caught.value.detail
+ assert "fake-secret" not in caught.value.detail
+
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ "error",
+ [
+ _client_error("RequestTimeout"),
+ _client_error("SlowDown"),
+ _client_error("ServiceUnavailable", status=503),
+ _client_error("InternalError", status=500),
+ _client_error("AccessDenied", status=500),
+ _client_error("NoSuchBucket", status=502),
+ _client_error("InvalidAccessKeyId", status=503),
+ _client_error("Throttling", "AssumeRole"),
+ _client_error("ThrottlingException", "AssumeRole"),
+ _client_error("RequestLimitExceeded"),
+ _client_error("UnknownError"),
+ IntermittentUploadPartTimeoutError(1),
+ botocore.exceptions.EndpointConnectionError(endpoint_url="https://example.com"),
+ botocore.exceptions.ConnectTimeoutError(endpoint_url="https://example.com"),
+ botocore.exceptions.ReadTimeoutError(endpoint_url="https://example.com"),
+ ExternalRoleArnNotConfiguredError(),
+ TimeoutError("fake-secret"),
+ ],
+ )
+ async def test_transient_errors_propagate_unchanged(self, error: Exception, finalize: bool) -> None:
+ ctx = _ctx()
+ writer = LocalS3Writer(ctx, mock.AsyncMock(), error)
+
+ with pytest.raises(type(error)) as caught:
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value is error
+ assert not isinstance(caught.value, DestinationConfigurationError)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py
index 8ad0cea66f14..edbb0581abf0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py
@@ -1,20 +1,44 @@
from collections.abc import AsyncIterator
+from dataclasses import replace
import pytest
+from unittest import mock
import pyarrow as pa
from parameterized import parameterized
-
-from products.batch_exports.backend.facade.destinations.snowflake import SnowflakeClient
+from snowflake.connector.errors import OperationalError, ProgrammingError
+
+from products.batch_exports.backend.facade.destinations.snowflake import (
+ InvalidPrivateKeyError,
+ SnowflakeAuthenticationError,
+ SnowflakeClient,
+ SnowflakeConnectionError,
+ SnowflakeFileNotLoadedError,
+ SnowflakeIncompatibleSchemaError,
+ SnowflakeInsufficientPrivilegesError,
+ SnowflakeIntegrationNotFoundError,
+ SnowflakeQueryClientTimeoutError,
+ SnowflakeQueryServerTimeoutError,
+ SnowflakeRetryableConnectionError,
+ SnowflakeWarehouseSuspendedError,
+ SnowflakeWarehouseUsageError,
+)
from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ MISSING_INTEGRATION_DETAIL,
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_snowflake import (
FakeSnowflakeClient,
FakeSnowflakeTable,
MergeMultiMatchError,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers import (
+ snowflake,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.snowflake import (
SnowflakeDestinationWriter,
UnrelatedTableExistsError,
@@ -88,6 +112,108 @@ async def _deliver(
await writer.finalize_run(ctx)
+class TestConfigurationErrors:
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ ("error", "detail_word"),
+ [
+ (SnowflakeAuthenticationError("fake-secret"), "password"),
+ (InvalidPrivateKeyError("fake-secret"), "private key"),
+ (SnowflakeConnectionError("fake-secret"), "account"),
+ (SnowflakeInsufficientPrivilegesError("fake-secret"), "privileges"),
+ (SnowflakeWarehouseUsageError("fake-secret"), "warehouse"),
+ (SnowflakeIntegrationNotFoundError(42, 1), "connection details"),
+ (ProgrammingError(msg="fake-secret", errno=3001), "privileges"),
+ (ProgrammingError(msg="fake-secret", errno=2043), "database or schema"),
+ ],
+ )
+ async def test_permanent_errors_are_configuration_errors(
+ self, error: Exception, detail_word: str, finalize: bool
+ ) -> None:
+ ctx = _ctx()
+ client = FakeSnowflakeClient()
+ writer = LocalSnowflakeWriter(ctx, client)
+ target = client if isinstance(error, ProgrammingError) else writer
+ method = "execute_async_query" if isinstance(error, ProgrammingError) else "_make_client"
+
+ with (
+ mock.patch.object(target, method, side_effect=error),
+ pytest.raises(DestinationConfigurationError, match=detail_word) as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+ assert caught.value.__cause__ is error
+ assert str(error) not in caught.value.detail
+ assert "fake-secret" not in caught.value.detail
+
+ @pytest.mark.parametrize("finalize", [False, True], ids=["write_batch", "finalize_run"])
+ @pytest.mark.parametrize(
+ "error",
+ [
+ SnowflakeRetryableConnectionError("fake-secret"),
+ SnowflakeWarehouseSuspendedError("fake-secret"),
+ SnowflakeQueryClientTimeoutError(1, "fake-secret", "RUNNING"),
+ SnowflakeQueryServerTimeoutError("fake-secret"),
+ SnowflakeFileNotLoadedError("charges", "FAILED", 1, "fake-secret"),
+ SnowflakeIncompatibleSchemaError("fake-secret"),
+ ProgrammingError(msg="fake-secret", errno=608),
+ ProgrammingError(msg="fake-secret", errno=90073),
+ OperationalError(msg="fake-secret"),
+ TimeoutError("fake-secret"),
+ UnrelatedTableExistsError("fake-secret"),
+ RuntimeError("fake-secret"),
+ ],
+ )
+ async def test_transient_errors_propagate_unchanged(self, error: Exception, finalize: bool) -> None:
+ ctx = _ctx()
+ client = FakeSnowflakeClient()
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ with (
+ mock.patch.object(client, "execute_async_query", side_effect=error),
+ pytest.raises(type(error)) as caught,
+ ):
+ if finalize:
+ await writer.finalize_run(ctx)
+ else:
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value is error
+ assert not isinstance(caught.value, DestinationConfigurationError)
+
+ @pytest.mark.parametrize("missing", ["integration", "deleted_integration", "private_key", "password"])
+ async def test_missing_connection_details_are_configuration_errors(self, missing: str) -> None:
+ ctx = replace(_ctx(), integration_id=None if missing == "integration" else 42)
+ writer = SnowflakeDestinationWriter(ctx)
+ creds = mock.Mock(
+ authentication_type="keypair" if missing == "private_key" else "password", private_key=None, password=None
+ )
+
+ with (
+ mock.patch.object(
+ snowflake,
+ "get_snowflake_integration",
+ return_value=creds,
+ side_effect=SnowflakeIntegrationNotFoundError(42, 1) if missing == "deleted_integration" else None,
+ ),
+ pytest.raises(DestinationConfigurationError, match="connection details") as caught,
+ ):
+ await writer.write_batch(
+ _batches(_rows([1], ["a"])), DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=False)
+ )
+
+ assert caught.value.detail == MISSING_INTEGRATION_DETAIL
+ assert str(caught.value).startswith(f"{ctx.destination_name}:")
+
+
class TestFullRefresh:
async def test_the_live_table_only_changes_once_the_run_completes(self) -> None:
client = FakeSnowflakeClient()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
index 86b6484cbb54..c778a7514d0a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
@@ -21,7 +21,8 @@ from __future__ import annotations
import io
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterator
+from contextlib import contextmanager
from typing import ClassVar
import pyarrow as pa
@@ -34,9 +35,13 @@ from products.batch_exports.backend.facade.destinations.databricks import (
FIVE_MINUTES,
ONE_HOUR,
ONE_MINUTE,
+ DatabricksCatalogNotFoundError,
DatabricksClient,
+ DatabricksConnectionError,
DatabricksField,
+ DatabricksInsufficientPermissionsError,
DatabricksIntegrationNotFoundError,
+ DatabricksSchemaNotFoundError,
handle_common_errors,
)
from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
@@ -44,6 +49,10 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ MISSING_INTEGRATION_DETAIL,
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
dedupe_merge_source,
)
@@ -57,6 +66,38 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
stamp_batch_index,
)
+CONNECTION_DETAIL = (
+ "Databricks could not connect. Check the server hostname and the service principal's client ID and secret, "
+ "then run the sync again."
+)
+PERMISSIONS_DETAIL = (
+ "The Databricks service principal lacks privileges on the catalog, schema or volume. "
+ "Grant USE CATALOG, USE SCHEMA, CREATE TABLE, CREATE VOLUME and WRITE VOLUME, then run the sync again."
+)
+CATALOG_DETAIL = (
+ "The Databricks catalog does not exist or the service principal cannot see it. "
+ "Check the catalog and grant the service principal access, then run the sync again."
+)
+SCHEMA_DETAIL = (
+ "The Databricks schema does not exist or the service principal cannot see it. "
+ "Check the schema and grant the service principal access, then run the sync again."
+)
+
+
+def _configuration_error_detail(err: Exception) -> str | None:
+ if isinstance(err, DatabricksConnectionError) and err.retryable is False:
+ return CONNECTION_DETAIL
+ if isinstance(err, DatabricksInsufficientPermissionsError):
+ return PERMISSIONS_DETAIL
+ if isinstance(err, DatabricksCatalogNotFoundError):
+ return CATALOG_DETAIL
+ if isinstance(err, DatabricksSchemaNotFoundError):
+ return SCHEMA_DETAIL
+ if isinstance(err, DatabricksIntegrationNotFoundError):
+ return MISSING_INTEGRATION_DETAIL
+ return None
+
+
_DATABRICKS_BY_ARROW = {
pa.bool_(): "BOOLEAN",
pa.int8(): "TINYINT",
@@ -202,11 +243,24 @@ class DatabricksDestinationWriter:
# --- connection -------------------------------------------------------------------
+ @contextmanager
+ def _configuration_errors(self) -> Iterator[None]:
+ try:
+ yield
+ except Exception as err:
+ detail = _configuration_error_detail(err)
+ if detail is not None:
+ raise DestinationConfigurationError(self._ctx.destination_name, detail) from err
+ raise
+
async def _make_client(self) -> DatabricksClient:
if self._ctx.integration_id is None:
- raise ValueError(f"Destination {self._ctx.destination_name} has no integration to connect with")
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL)
- creds = await _load_integration(self._ctx.integration_id, self._ctx.team_id)
+ try:
+ creds = await _load_integration(self._ctx.integration_id, self._ctx.team_id)
+ except DatabricksIntegrationNotFoundError as err:
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL) from err
return DatabricksClient(
server_hostname=creds.server_hostname,
@@ -317,6 +371,12 @@ class DatabricksDestinationWriter:
async def write_batch(
self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ with self._configuration_errors():
+ return await self._write_batch(batches, ctx)
+
+ async def _write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
) -> BatchWriteOutcome:
run = ctx.run
full_refresh = run.is_full_refresh
@@ -468,6 +528,10 @@ class DatabricksDestinationWriter:
return batch.num_rows
async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await self._finalize_run(ctx)
+
+ async def _finalize_run(self, ctx: DestinationRunContext) -> None:
"""Publish a full refresh by swapping the staging table into place."""
if not ctx.is_full_refresh:
return
@@ -516,6 +580,10 @@ class DatabricksDestinationWriter:
)
async def abort_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await self._abort_run(ctx)
+
+ async def _abort_run(self, ctx: DestinationRunContext) -> None:
# The next run stages under its own id, so a leftover table costs storage only.
_assert_safe_identifier(ctx.table_name, "table name")
client = await self._make_client()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
index a9c40922a9c1..eec3c9bee03d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
@@ -22,15 +22,26 @@ Wiring that up here is follow-up work.
from __future__ import annotations
import json
+from collections.abc import AsyncIterator, Iterator
+from contextlib import contextmanager
from typing import Any, ClassVar, cast
import pyarrow as pa
from psycopg import sql
+from psycopg.errors import InsufficientPrivilege
from posthog.models.integration import Integration, RedshiftIntegration
from products.batch_exports.backend.facade.destinations.postgres import Fields, PostgreSQLClient
from products.batch_exports.backend.facade.destinations.redshift import RedshiftClient
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ BatchWriteOutcome,
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import (
PostgresDestinationWriter,
)
@@ -43,6 +54,18 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
# reports the same overflow as `StringLimitExceededError` and never retries it.
VARCHAR_MAX = "VARCHAR(MAX)"
+PERMISSIONS_DETAIL = (
+ "The Redshift user lacks permissions. Grant the user USAGE and CREATE on the schema. "
+ "Grant rights on the tables it syncs, then run the sync again."
+)
+
+
+def _configuration_error_detail(err: Exception) -> str | None:
+ if isinstance(err, InsufficientPrivilege):
+ return PERMISSIONS_DETAIL
+ return None
+
+
_REDSHIFT_BY_ARROW = {
pa.bool_(): "BOOLEAN",
pa.int8(): "SMALLINT",
@@ -88,6 +111,30 @@ class RedshiftDestinationWriter(PostgresDestinationWriter):
integration_kind: ClassVar[str] = RedshiftIntegration.integration_kind
+ @contextmanager
+ def _configuration_errors(self) -> Iterator[None]:
+ try:
+ yield
+ except Exception as err:
+ detail = _configuration_error_detail(err)
+ if detail is not None:
+ raise DestinationConfigurationError(self._ctx.destination_name, detail) from err
+ raise
+
+ async def write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ with self._configuration_errors():
+ return await super().write_batch(batches, ctx)
+
+ async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await super().finalize_run(ctx)
+
+ async def abort_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await super().abort_run(ctx)
+
def _client_from_integration(self, integration: Integration) -> PostgreSQLClient:
return RedshiftClient.from_inputs(RedshiftIntegration(integration), database=self._database)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
index bd214fa3878a..f4b173f6e2a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
@@ -38,8 +38,8 @@ import json
import asyncio
import datetime as dt
import functools
-from collections.abc import AsyncIterator, Awaitable, Callable
-from contextlib import asynccontextmanager
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
+from contextlib import asynccontextmanager, contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, ClassVar, Literal
@@ -57,6 +57,7 @@ from products.batch_exports.backend.facade.destinations.s3 import (
S3_SUPPORTED_COMPRESSIONS,
ConcurrentS3Consumer,
IntermittentUploadPartTimeoutError,
+ InvalidCredentialsError,
PolicyStatement,
S3IntegrationNotFoundError,
get_credentials_using_user_aws_role,
@@ -83,6 +84,37 @@ logger = structlog.get_logger(__name__)
ParquetCompression = Literal["gzip", "brotli", "lz4", "zstd", "snappy", "none"]
DEFAULT_COMPRESSION: ParquetCompression = "zstd"
+CREDENTIALS_DETAIL = "S3 authentication failed. Check the access key ID and secret, then run the sync again."
+BUCKET_DETAIL = (
+ "The S3 bucket does not exist or is in another region. Check the bucket name and region, then run the sync again."
+)
+PERMISSIONS_DETAIL = (
+ "S3 denied access to the bucket path. Grant s3:PutObject and s3:AbortMultipartUpload on the bucket path, "
+ "then run the sync again."
+)
+ROLE_DETAIL = (
+ "PostHog cannot assume the role. Check the role ARN and the trust policy with the external ID, "
+ "then run the sync again."
+)
+
+
+def _configuration_error_detail(err: Exception) -> str | None:
+ if isinstance(err, InvalidCredentialsError):
+ return ROLE_DETAIL
+ if not isinstance(err, botocore.exceptions.ClientError):
+ return None
+ if err.response.get("ResponseMetadata", {}).get("HTTPStatusCode", 0) >= 500:
+ return None
+ code = err.response.get("Error", {}).get("Code")
+ if code in ("InvalidAccessKeyId", "SignatureDoesNotMatch"):
+ return CREDENTIALS_DETAIL
+ if code == "NoSuchBucket":
+ return BUCKET_DETAIL
+ if code in ("AccessDenied", "AccessDeniedException"):
+ return ROLE_DETAIL if err.operation_name == "AssumeRole" else PERMISSIONS_DETAIL
+ return None
+
+
# The destination's `config` is an unvalidated JSONField, so whatever a user puts in it reaches
# pyarrow directly. Anything outside this set fails mid-write, several hundred MiB in.
SUPPORTED_COMPRESSIONS = frozenset(S3_SUPPORTED_COMPRESSIONS["Parquet"]) | {"none"}
@@ -302,6 +334,16 @@ class S3DestinationWriter:
# --- connection -------------------------------------------------------------------
+ @contextmanager
+ def _configuration_errors(self) -> Iterator[None]:
+ try:
+ yield
+ except Exception as err:
+ detail = _configuration_error_detail(err)
+ if detail is not None:
+ raise DestinationConfigurationError(self._ctx.destination_name, detail) from err
+ raise
+
@asynccontextmanager
async def _client(self) -> AsyncIterator[S3Client]:
"""Their client, entered so its aiohttp session is closed on the way out.
@@ -375,6 +417,12 @@ class S3DestinationWriter:
async def write_batch(
self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ with self._configuration_errors():
+ return await self._write_batch(batches, ctx)
+
+ async def _write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
) -> BatchWriteOutcome:
first = await anext(batches, None)
if first is None:
@@ -403,6 +451,10 @@ class S3DestinationWriter:
return None if self._compression == "none" else self._compression
async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await self._finalize_run(ctx)
+
+ async def _finalize_run(self, ctx: DestinationRunContext) -> None:
"""Write a manifest, which is how a reader tells a finished run from an abandoned one.
It carries no file list. `finalize_run` runs on a writer that may have written none of
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
index 9f21cc8c8ecf..448a6c75be94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
@@ -24,18 +24,26 @@ and breaking a later merge.
from __future__ import annotations
import io
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterator
+from contextlib import contextmanager
from typing import ClassVar
import pyarrow as pa
import pyarrow.parquet as pq
+from snowflake.connector.errors import ProgrammingError
from products.batch_exports.backend.facade.destinations.snowflake import (
+ InvalidPrivateKeyError,
NamedBytesIO,
+ SnowflakeAuthenticationError,
SnowflakeClient,
+ SnowflakeConnectionError,
SnowflakeField,
+ SnowflakeInsufficientPrivilegesError,
+ SnowflakeIntegrationNotFoundError,
SnowflakeTable,
SnowflakeType,
+ SnowflakeWarehouseUsageError,
get_snowflake_integration,
load_private_key,
)
@@ -44,6 +52,10 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ MISSING_INTEGRATION_DETAIL,
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
dedupe_merge_source,
)
@@ -60,6 +72,45 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
quote_identifier,
)
+AUTHENTICATION_DETAIL = (
+ "Snowflake authentication failed. Check the user and password or private key, then run the sync again."
+)
+CONNECTION_DETAIL = (
+ "Snowflake could not connect. Check the account, user, credentials and role, then run the sync again."
+)
+PRIVILEGES_DETAIL = (
+ "The Snowflake role lacks privileges. Grant it privileges to create tables and load data in the database and schema, "
+ "then run the sync again."
+)
+WAREHOUSE_DETAIL = (
+ "The Snowflake warehouse does not exist or the role lacks USAGE. "
+ "Check the warehouse and grant the role USAGE, then run the sync again."
+)
+DATABASE_SCHEMA_DETAIL = (
+ "The Snowflake database or schema does not exist or the role cannot use it. "
+ "Check the database and schema and grant the role access, then run the sync again."
+)
+
+
+def _configuration_error_detail(err: Exception) -> str | None:
+ if isinstance(err, SnowflakeAuthenticationError | InvalidPrivateKeyError):
+ return AUTHENTICATION_DETAIL
+ if isinstance(err, SnowflakeConnectionError):
+ return CONNECTION_DETAIL
+ if isinstance(err, SnowflakeInsufficientPrivilegesError):
+ return PRIVILEGES_DETAIL
+ if isinstance(err, SnowflakeWarehouseUsageError):
+ return WAREHOUSE_DETAIL
+ if isinstance(err, SnowflakeIntegrationNotFoundError):
+ return MISSING_INTEGRATION_DETAIL
+ if isinstance(err, ProgrammingError):
+ if err.errno == 3001:
+ return PRIVILEGES_DETAIL
+ if err.errno == 2043:
+ return DATABASE_SCHEMA_DETAIL
+ return None
+
+
_SNOWFLAKE_BY_ARROW = {
pa.bool_(): "BOOLEAN",
pa.int8(): "NUMBER(38, 0)",
@@ -215,22 +266,35 @@ class SnowflakeDestinationWriter:
# --- connection -------------------------------------------------------------------
+ @contextmanager
+ def _configuration_errors(self) -> Iterator[None]:
+ try:
+ yield
+ except Exception as err:
+ detail = _configuration_error_detail(err)
+ if detail is not None:
+ raise DestinationConfigurationError(self._ctx.destination_name, detail) from err
+ raise
+
async def _make_client(self) -> SnowflakeClient:
if self._ctx.integration_id is None:
- raise ValueError(f"Destination {self._ctx.destination_name} has no integration to connect with")
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL)
- creds = await get_snowflake_integration(self._ctx.integration_id, self._ctx.team_id)
+ try:
+ creds = await get_snowflake_integration(self._ctx.integration_id, self._ctx.team_id)
+ except SnowflakeIntegrationNotFoundError as err:
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL) from err
private_key: bytes | None = None
password: str | None = None
if creds.authentication_type == "keypair":
- if creds.private_key is None:
- raise ValueError(
- f"Destination {self._ctx.destination_name} has keypair authentication but no private key"
- )
+ if not creds.private_key:
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL)
private_key = load_private_key(creds.private_key, creds.private_key_passphrase)
else:
password = creds.password
+ if not password:
+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL)
return SnowflakeClient(
user=creds.user,
@@ -319,6 +383,12 @@ class SnowflakeDestinationWriter:
async def write_batch(
self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ with self._configuration_errors():
+ return await self._write_batch(batches, ctx)
+
+ async def _write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
) -> BatchWriteOutcome:
run = ctx.run
full_refresh = run.is_full_refresh
@@ -455,6 +525,10 @@ class SnowflakeDestinationWriter:
return batch.num_rows
async def finalize_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await self._finalize_run(ctx)
+
+ async def _finalize_run(self, ctx: DestinationRunContext) -> None:
"""Publish a full refresh by swapping the staging table into place."""
if not ctx.is_full_refresh:
return
@@ -495,6 +569,10 @@ class SnowflakeDestinationWriter:
)
async def abort_run(self, ctx: DestinationRunContext) -> None:
+ with self._configuration_errors():
+ await self._abort_run(ctx)
+
+ async def _abort_run(self, ctx: DestinationRunContext) -> None:
# The next run stages under its own id, so a leftover table costs storage only.
client = await self._make_client()
async with client.connect():