: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(data-warehouse): fail destination delivery fast on configuration errors (#112162)
Tom Owers3d4e9a0211ca
diff --git a/products/batch_exports/backend/facade/destinations/azure_blob.py b/products/batch_exports/backend/facade/destinations/azure_blob.pyindex 3ff483c0ad0f..cb91c1b4b353 100644--- a/products/batch_exports/backend/facade/destinations/azure_blob.py+++ b/products/batch_exports/backend/facade/destinations/azure_blob.py@@ -9,6 +9,7 @@ Importing this module loads the destination's vendor SDK, so keep it off the"""from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (+ AzureBlobIntegrationNotFoundError,MalformedConnectionStringError,_get_azure_blob_integration as get_azure_blob_integration,_is_authorization_failure_response_error as is_authorization_failure_response_error,@@ -17,6 +18,7 @@ from products.batch_exports.backend.temporal.destinations.constants import AZURE__all__ = ["AZURE_BLOB_SUPPORTED_COMPRESSIONS",+ "AzureBlobIntegrationNotFoundError","MalformedConnectionStringError","get_azure_blob_integration","is_authorization_failure_response_error",diff --git a/products/batch_exports/backend/facade/destinations/postgres.py b/products/batch_exports/backend/facade/destinations/postgres.pyindex ea585e1f8f97..27001815dc01 100644--- a/products/batch_exports/backend/facade/destinations/postgres.py+++ b/products/batch_exports/backend/facade/destinations/postgres.py@@ -11,6 +11,7 @@ Importing this module loads the destination's vendor SDK, so keep it off thefrom products.batch_exports.backend.temporal.destinations.postgres_batch_export import (Fields,PostgreSQLClient,+ PostgreSQLConnectionError,PostgreSQLIntegrationNotFoundError,run_in_retryable_transaction,)@@ -18,6 +19,7 @@ from products.batch_exports.backend.temporal.destinations.postgres_batch_export__all__ = ["Fields","PostgreSQLClient",+ "PostgreSQLConnectionError","PostgreSQLIntegrationNotFoundError","run_in_retryable_transaction",]diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.pyindex cd054d8f125b..767fe8e9b8e0 100644--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py@@ -332,10 +332,16 @@ class PostgreSQLClient:@contextlib.asynccontextmanagerasync def connect(self,+ *,+ is_error_retryable: typing.Callable[[Exception], bool] | None = None,) -> typing.AsyncIterator[typing.Self]:"""Context manager for a PostgreSQL connection, backed by `psycopg`.Connection parameters are set when initializing a client.++ `is_error_retryable` lets a caller stop the connect retries early on an error it knows+ fails the same way every time. The `PostgreSQLConnectionError` raised then keeps that+ error as its `__cause__`. Without it, every `OperationalError` is retried."""max_attempts = 5connect: typing.Callable[..., typing.Awaitable[psycopg.AsyncConnection]] = (@@ -343,6 +349,7 @@ class PostgreSQLClient:psycopg.AsyncConnection.connect,max_attempts=max_attempts,retryable_exceptions=(psycopg.OperationalError, psycopg.errors.ConnectionTimeout),+ is_exception_retryable=is_error_retryable or (lambda _: True),))diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.pyindex 3adc29d4fd39..d8b2eff41b85 100644--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py@@ -261,7 +261,11 @@ class ClientErrorGroup(ExceptionGroup):class RedshiftClient(PostgreSQLClient):@contextlib.asynccontextmanager- async def connect(self) -> collections.abc.AsyncIterator[typing.Self]:+ async def connect(+ self,+ *,+ is_error_retryable: typing.Callable[[Exception], bool] | None = None,+ ) -> collections.abc.AsyncIterator[typing.Self]:"""Manage a Redshift connection.This just yields a Postgres connection but we adjust a couple of things required for@@ -273,7 +277,7 @@ class RedshiftClient(PostgreSQLClient):psycopg._encodings._py_codecs["UNICODE"] = "utf-8"psycopg._encodings.py_codecs.update((k.encode(), v) for k, v in psycopg._encodings._py_codecs.items())- async with super().connect():+ async with super().connect(is_error_retryable=is_error_retryable):self.connection.prepare_threshold = Noneyield selfdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.pyindex d41e3e96e437..6e96dc1adb04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py@@ -32,6 +32,11 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.regisfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.builtin_writers import (ensure_builtin_destination_writers_registered,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DestinationConfigurationError,+ DestinationDeliveryError,+ is_configuration_failure_of,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.parquet_source import (aiter_record_batches,)@@ -44,19 +49,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinelogger = structlog.get_logger(__name__)-class DestinationDeliveryError(Exception):- """One destination could not take the batch, so the batch is not done.-- Carries the destination's name so a single job's `latest_error` still says which- destination stopped the sync.- """-- def __init__(self, destination_name: str, cause: Exception) -> None:- self.destination_name = destination_name- self.cause = cause- super().__init__(f"{destination_name}: {cause}")--def external_destinations_for(export_signal: ExportSignalMessage) -> list[ExternalDataDestination]:"""The run's destinations, minus the PostHog warehouse, in a stable order.@@ -299,6 +291,8 @@ def deliver_batch_to_destinations(error=str(e),msg=f"Failed writing to {destination.name} ({run_ctx.table_name}): {e}",)+ if isinstance(e, DestinationConfigurationError):+ raiseraise DestinationDeliveryError(destination.name, e) from erows_written = outcome.rows_written if outcome else 0@@ -328,9 +322,20 @@ async def _write(return await writer.write_batch(aiter_record_batches(export_signal.s3_path), batch_ctx)-def abort_destinations(export_signal: ExportSignalMessage) -> None:- """Let each writer drop what a run that will not finish left staged."""+def abort_destinations(export_signal: ExportSignalMessage, failure_reason: str = "") -> None:+ """Let each writer drop what a run that will not finish left staged.++ A destination that failed the run with a configuration error is skipped. The same settings+ refuse the abort's connection too, so a try costs connection attempts and drops nothing.+ """for destination in external_destinations_for(export_signal):+ if failure_reason and is_configuration_failure_of(failure_reason, destination.name):+ logger.info(+ "destination_abort_skipped_configuration_error",+ destination_name=destination.name,+ destination_type=destination.type,+ )+ continuerun_ctx = _run_context(export_signal, destination)try:ensure_builtin_destination_writers_registered()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.pynew file mode 100644index 000000000000..5f55db73aef3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.py@@ -0,0 +1,50 @@+"""Errors a destination delivery raises.++Kept apart from `delivery` so a writer can raise them without importing the delivery path, and+so the load consumer can match on the marker without importing any writer.+"""++from __future__ import annotations++# The load consumer matches this substring to fail a run on its first attempt. Changing it+# silently turns every configuration error back into a retried, reported failure.+DESTINATION_CONFIGURATION_ERROR_MARKER = "Destination configuration error"++MISSING_INTEGRATION_DETAIL = (+ "The destination's connection details no longer exist. Connect the destination again, then run the sync again."+)+++class DestinationDeliveryError(Exception):+ """One destination could not take the batch, so the batch is not done.++ Carries the destination's name so a single job's `latest_error` still says which+ destination stopped the sync.+ """++ def __init__(self, destination_name: str, cause: Exception | str) -> None:+ self.destination_name = destination_name+ self.cause = cause+ super().__init__(f"{destination_name}: {cause}")+++class DestinationConfigurationError(DestinationDeliveryError):+ """The destination's own settings stop every connection, so no retry can succeed.++ Raised before anything is staged, which lets the run fail on its first attempt and lets+ the abort path skip a destination it could not connect to anyway.+ """++ def __init__(self, destination_name: str, detail: str) -> None:+ self.detail = detail+ super().__init__(destination_name, f"{DESTINATION_CONFIGURATION_ERROR_MARKER}. {detail}")+++def is_configuration_failure_of(reason: str, destination_name: str) -> bool:+ """Whether a run's failure `reason` is a configuration error raised by this destination.++ The prefix must start the reason or follow a `: ` separator, so a destination named `Prod`+ does not match a failure of one named `My Prod`.+ """+ prefix = f"{destination_name}: {DESTINATION_CONFIGURATION_ERROR_MARKER}"+ return reason.startswith(prefix) or f": {prefix}" in reasondiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.pyindex 9742d7def0be..1beea8a75626 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py@@ -19,9 +19,16 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.regissnapshot_registered_writers,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load import delivery+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.builtin_writers import (+ ensure_builtin_destination_writers_registered,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import (destination_table_name,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DESTINATION_CONFIGURATION_ERROR_MARKER,+ DestinationConfigurationError,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage@@ -30,6 +37,7 @@ class RecordingWriter:runs_post_load = Falsecalls: list[tuple[str, str, int]] = []fail_for: set[str] = set()+ configuration_error_for: set[str] = set()def __init__(self, ctx) -> None:self._ctx = ctx@@ -40,6 +48,8 @@ class RecordingWriter:async def write_batch(self, batches, batch_ctx) -> BatchWriteOutcome:if self._ctx.destination_name in RecordingWriter.fail_for:raise RuntimeError("destination unreachable")+ if self._ctx.destination_name in RecordingWriter.configuration_error_for:+ raise DestinationConfigurationError(self._ctx.destination_name, "The host name does not exist.")RecordingWriter.calls.append(("write", self._ctx.destination_name, batch_ctx.batch_index))return BatchWriteOutcome(rows_written=1)@@ -55,7 +65,11 @@ class DeliveryTestCase(BaseTest):super().setUp()RecordingWriter.calls = []RecordingWriter.fail_for = set()+ RecordingWriter.configuration_error_for = set()+ # Registered before the snapshot, so the first delivery in the process cannot replace the+ # fakes below, and the cleanup puts the real writers back.+ ensure_builtin_destination_writers_registered()# The registry is process-global, so these fakes have to come back out or every later# test sees destination types this deployment cannot really write.self.addCleanup(restore_registered_writers, snapshot_registered_writers())@@ -190,18 +204,31 @@ class TestDelivery(DeliveryTestCase):RecordingWriter.calls = []RecordingWriter.fail_for = set()+ RecordingWriter.configuration_error_for = set()delivery.deliver_batch_to_destinations(signal)assert self._writes() == [last.name]- def test_the_error_names_the_destination_that_stopped_the_sync(self) -> None:+ @parameterized.expand(+ [+ ("transient", "fail_for", "customer redshift: destination unreachable"),+ (+ "configuration",+ "configuration_error_for",+ f"customer redshift: {DESTINATION_CONFIGURATION_ERROR_MARKER}. The host name does not exist.",+ ),+ ]+ )+ def test_the_error_names_the_destination_that_stopped_the_sync(+ self, _name: str, failure_attribute: str, expected_message: str+ ) -> None:a = self._destination("customer redshift")- RecordingWriter.fail_for = {"customer redshift"}+ setattr(RecordingWriter, failure_attribute, {"customer redshift"})with self.assertRaises(delivery.DestinationDeliveryError) as caught:delivery.deliver_batch_to_destinations(self._signal([str(a.id)]))- assert "customer redshift" in str(caught.exception)+ assert str(caught.exception) == expected_messagedef test_the_final_batch_publishes_each_destination(self) -> None:a = self._destination("warehouse a")@@ -252,6 +279,36 @@ class TestDelivery(DeliveryTestCase):assert not self._writes()+class TestAbortDestinations(DeliveryTestCase):+ @parameterized.expand(+ [+ ("no_reason", "", ["Prod", "My Prod"]),+ ("unrelated_failure", "max retries exceeded: Prod: destination unreachable", ["Prod", "My Prod"]),+ ("configuration_error_of_one", f"Prod: {DESTINATION_CONFIGURATION_ERROR_MARKER}. Bad host.", ["My Prod"]),+ (+ "configuration_error_of_the_other",+ f"My Prod: {DESTINATION_CONFIGURATION_ERROR_MARKER}. Bad host.",+ ["Prod"],+ ),+ (+ "wrapped_configuration_error",+ f"permanent apply error: Prod: {DESTINATION_CONFIGURATION_ERROR_MARKER}. Bad host.",+ ["My Prod"],+ ),+ ]+ )+ def test_skips_only_the_destination_that_failed_on_its_configuration(+ self, _name: str, failure_reason: str, expected_aborted: list[str]+ ) -> None:+ a = self._destination("Prod")+ b = self._destination("My Prod", ExternalDataDestination.Type.SNOWFLAKE)++ delivery.abort_destinations(self._signal([str(a.id), str(b.id)]), failure_reason=failure_reason)++ aborted = [name for kind, name, _ in RecordingWriter.calls if kind == "abort"]+ assert sorted(aborted) == sorted(expected_aborted)++class TestDestinationTableName(DeliveryTestCase):"""The name a destination writes under, which a customer sees in their own database."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_configuration_errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_configuration_errors.pynew file mode 100644index 000000000000..0233746559cc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_configuration_errors.py@@ -0,0 +1,301 @@+import socket++import pytest+from unittest import mock++import psycopg++from posthog.models.integration import Integration++from products.batch_exports.backend.facade.destinations.postgres import PostgreSQLClient, PostgreSQLConnectionError+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import DestinationRunContext+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DESTINATION_CONFIGURATION_ERROR_MARKER,+ MISSING_INTEGRATION_DETAIL,+ DestinationConfigurationError,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers import (+ postgres,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import (+ ACCESS_RULE_DETAIL,+ AUTHENTICATION_FAILED_DETAIL,+ HOST_NOT_FOUND_DETAIL,+ IPV6_ONLY_HOST_DETAIL,+ NETWORK_UNREACHABLE_DETAIL,+ UNKNOWN_DATABASE_DETAIL,+ PostgresDestinationWriter,+ connect_configuration_error_detail,+ host_configuration_error_detail,+)++HOST = "db.example.com"+V4 = "192.0.2.10"+V6 = "2001:db8::10"+++def _attempt_failed(reason: str, address: str = V4) -> str:+ return f'connection failed: connection to server at "{HOST}" ({address}), port 5432 failed: {reason}'+++def _addrinfo(*addresses: str) -> list[tuple]:+ return [+ (+ socket.AF_INET6 if ":" in address else socket.AF_INET,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ (address, 5432, 0, 0) if ":" in address else (address, 5432),+ )+ for address in addresses+ ]+++def _ctx(integration_id: int | None = 1) -> DestinationRunContext:+ return DestinationRunContext(+ team_id=1,+ schema_id="schema",+ source_id="source",+ job_id="job",+ run_uuid="run",+ destination_id="destination",+ destination_type="Postgres",+ destination_name="Prod",+ table_name="orders",+ sync_type="full_refresh",+ integration_id=integration_id,+ )+++class _FixedClientWriter(PostgresDestinationWriter):+ def __init__(self, host: str) -> None:+ super().__init__(_ctx())+ self._host = host++ async def _make_client(self) -> PostgreSQLClient:+ return PostgreSQLClient(+ user="posthog", password="secret", host=self._host, port=5432, database="postgres", ssl_mode="prefer"+ )+++async def _open(writer: PostgresDestinationWriter) -> None:+ async with writer._client():+ pass+++class TestConnectConfigurationErrorDetail:+ @pytest.mark.parametrize(+ ("_name", "err", "expected"),+ [+ (+ "ipv6_unreachable",+ psycopg.OperationalError(_attempt_failed("Network is unreachable", V6)),+ NETWORK_UNREACHABLE_DETAIL,+ ),+ (+ "wrong_password",+ psycopg.OperationalError(_attempt_failed('FATAL: password authentication failed for user "loader"')),+ AUTHENTICATION_FAILED_DETAIL,+ ),+ (+ "unknown_role",+ psycopg.OperationalError(_attempt_failed('FATAL: role "loader" does not exist')),+ AUTHENTICATION_FAILED_DETAIL,+ ),+ (+ "no_access_rule",+ psycopg.OperationalError(_attempt_failed('FATAL: no pg_hba.conf entry for host "198.51.100.7"')),+ ACCESS_RULE_DETAIL,+ ),+ (+ "unknown_database",+ psycopg.OperationalError(_attempt_failed('FATAL: database "analytics" does not exist')),+ UNKNOWN_DATABASE_DETAIL,+ ),+ ("invalid_password_class", psycopg.errors.InvalidPassword("rejected"), AUTHENTICATION_FAILED_DETAIL),+ ("invalid_catalog_class", psycopg.errors.InvalidCatalogName("missing"), UNKNOWN_DATABASE_DETAIL),+ (+ "last_attempt_rejected_the_password",+ psycopg.OperationalError(+ _attempt_failed('FATAL: password authentication failed for user "loader"')+ + "\nMultiple connection attempts failed. All failures were:\n- "+ + _attempt_failed("Network is unreachable", V6)+ ),+ AUTHENTICATION_FAILED_DETAIL,+ ),+ ("connect_timeout", psycopg.errors.ConnectionTimeout("connection timeout expired"), None),+ (+ "last_attempt_timed_out_after_unreachable_ipv6",+ psycopg.OperationalError(+ _attempt_failed("timeout expired")+ + "\nMultiple connection attempts failed. All failures were:\n- "+ + _attempt_failed("Network is unreachable", V6)+ + "\n- "+ + _attempt_failed("timeout expired")+ ),+ None,+ ),+ ("connection_reset", psycopg.OperationalError(_attempt_failed("Connection reset by peer")), None),+ (+ "server_shutting_down",+ psycopg.OperationalError(_attempt_failed("FATAL: the database system is shutting down")),+ None,+ ),+ (+ "too_many_clients",+ psycopg.OperationalError(_attempt_failed("FATAL: sorry, too many clients already")),+ None,+ ),+ (+ "server_closed_connection",+ psycopg.OperationalError(_attempt_failed("server closed the connection unexpectedly")),+ None,+ ),+ ("not_a_psycopg_error", RuntimeError("Network is unreachable"), None),+ ],+ )+ def test_classifies_connect_errors(self, _name: str, err: Exception, expected: str | None) -> None:+ assert connect_configuration_error_detail(err) == expected+++class TestHostConfigurationErrorDetail:+ @pytest.mark.parametrize(+ ("_name", "host", "resolution", "ipv6_route", "expected"),+ [+ ("ipv6_only_without_route", HOST, _addrinfo(V6), False, IPV6_ONLY_HOST_DETAIL),+ ("ipv6_only_with_route", HOST, _addrinfo(V6), True, None),+ ("dual_stack_without_route", HOST, _addrinfo(V6, V4), False, None),+ ("ipv4_only_without_route", HOST, _addrinfo(V4), False, None),+ ("ipv6_literal_without_route", V6, None, False, IPV6_ONLY_HOST_DETAIL),+ ("bracketed_ipv6_literal_without_route", f"[{V6}]", None, False, IPV6_ONLY_HOST_DETAIL),+ ("ipv4_literal_without_route", V4, None, False, None),+ ("unix_socket", "/var/run/postgresql", None, False, None),+ (+ "name_does_not_exist",+ HOST,+ socket.gaierror(socket.EAI_NONAME, "Name or service not known"),+ True,+ HOST_NOT_FOUND_DETAIL,+ ),+ (+ "resolver_temporarily_failing",+ HOST,+ socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution"),+ True,+ None,+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_classifies_the_host(+ self,+ _name: str,+ host: str,+ resolution: list[tuple] | Exception | None,+ ipv6_route: bool,+ expected: str | None,+ ) -> None:+ lookup = (+ mock.Mock(side_effect=resolution)+ if isinstance(resolution, Exception)+ else mock.Mock(return_value=resolution)+ )+ with (+ mock.patch("socket.getaddrinfo", lookup),+ mock.patch.object(postgres, "has_ipv6_route", return_value=ipv6_route),+ ):+ assert await host_configuration_error_detail(host, 5432) == expected++ if resolution is None:+ lookup.assert_not_called()++ @pytest.mark.asyncio+ async def test_a_resolver_that_hangs_leaves_the_decision_to_connect(self) -> None:+ with (+ mock.patch.object(postgres, "_resolve", side_effect=TimeoutError),+ mock.patch.object(postgres, "has_ipv6_route", return_value=False),+ ):+ assert await host_configuration_error_detail(HOST, 5432) is None+++class TestWriterClient:+ @pytest.mark.parametrize(+ ("_name", "integration_id"),+ [+ ("no_integration", None),+ ("integration_deleted", 42),+ ],+ )+ @pytest.mark.asyncio+ async def test_a_missing_integration_is_a_configuration_error(self, _name: str, integration_id: int | None) -> None:+ writer = PostgresDestinationWriter(_ctx(integration_id))++ with (+ mock.patch.object(Integration.objects, "aget", side_effect=Integration.DoesNotExist),+ mock.patch.object(psycopg.AsyncConnection, "connect") as connect,+ pytest.raises(DestinationConfigurationError) as caught,+ ):+ await _open(writer)++ assert str(caught.value) == f"Prod: {DESTINATION_CONFIGURATION_ERROR_MARKER}. {MISSING_INTEGRATION_DETAIL}"+ connect.assert_not_called()++ @pytest.mark.asyncio+ async def test_an_ipv6_only_host_fails_without_connecting(self) -> None:+ with (+ mock.patch("socket.getaddrinfo", return_value=_addrinfo(V6)),+ mock.patch.object(postgres, "has_ipv6_route", return_value=False),+ mock.patch.object(psycopg.AsyncConnection, "connect") as connect,+ pytest.raises(DestinationConfigurationError) as caught,+ ):+ await _open(_FixedClientWriter(HOST))++ assert IPV6_ONLY_HOST_DETAIL in str(caught.value)+ connect.assert_not_called()++ @pytest.mark.parametrize(+ ("_name", "error", "expected_error", "expected_attempts"),+ [+ (+ "configuration_error_stops_at_once",+ psycopg.OperationalError(_attempt_failed('FATAL: password authentication failed for user "loader"')),+ DestinationConfigurationError,+ 1,+ ),+ (+ "transient_error_keeps_its_retries",+ psycopg.OperationalError(_attempt_failed("FATAL: sorry, too many clients already")),+ PostgreSQLConnectionError,+ 5,+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_connect_retries_only_transient_errors(+ self, _name: str, error: Exception, expected_error: type[Exception], expected_attempts: int+ ) -> None:+ with (+ mock.patch("socket.getaddrinfo", return_value=_addrinfo(V4)),+ mock.patch.object(psycopg.AsyncConnection, "connect", side_effect=error) as connect,+ mock.patch("asyncio.sleep", new_callable=mock.AsyncMock),+ pytest.raises(expected_error),+ ):+ await _open(_FixedClientWriter(HOST))++ assert connect.call_count == expected_attempts++ @pytest.mark.asyncio+ async def test_an_error_inside_the_connection_is_not_reclassified(self) -> None:+ connection = mock.AsyncMock()+ connection.__aenter__.return_value = connection+ failure = PostgreSQLConnectionError("Not connected")++ with (+ mock.patch("socket.getaddrinfo", return_value=_addrinfo(V4)),+ mock.patch.object(psycopg.AsyncConnection, "connect", return_value=connection),+ pytest.raises(PostgreSQLConnectionError) as caught,+ ):+ async with _FixedClientWriter(HOST)._client():+ raise failure++ assert caught.value is failurediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.pyindex a805a7f5c3aa..9bd3b5b2ff70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py@@ -51,6 +51,7 @@ from posthog.models.integration.azure_blob import EndpointNotAllowedError, validfrom products.batch_exports.backend.facade.destinations.azure_blob import (AZURE_BLOB_SUPPORTED_COMPRESSIONS,+ AzureBlobIntegrationNotFoundError,MalformedConnectionStringError,get_azure_blob_integration,is_authorization_failure_response_error,@@ -61,6 +62,10 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contrDestinationBatchContext,DestinationRunContext,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ MISSING_INTEGRATION_DETAIL,+ DestinationConfigurationError,+)ParquetCompression = Literal["gzip", "brotli", "lz4", "zstd", "snappy", "none"]DEFAULT_COMPRESSION: ParquetCompression = "zstd"@@ -78,35 +83,21 @@ MAX_BLOCK_SIZE = 4 * 1024 * 1024READ_TIMEOUT_SECONDS = 600-class AzureBlobDestinationConfigurationError(ValueError):- """The destination's config cannot produce a valid blob write."""---class ContainerNotFoundError(Exception):- """Raised when the configured container does not exist.-- Containers are not created here, so this is the customer's to fix.- """-- def __init__(self, container: str) -> None:- super().__init__(- f"The container '{container}' does not exist in this storage account. "- "Create it, or point the destination at an existing container, then run the sync again."- )---class MissingContainerPermissionsError(Exception):- """Raised when the connection string cannot write to the container.+def container_not_found_detail(container: str) -> str:+ # Containers are not created here, so this is the customer's to fix.+ return (+ f"The container '{container}' does not exist in this storage account. "+ "Create it, or point the destination at an existing container, then run the sync again."+ )- Batch exports' own `MissingRequiredPermissionsError` says "batch export", which reads- wrong on a sync. Only the classifier behind it is shared.- """- def __init__(self, container: str) -> None:- super().__init__(- f"These credentials cannot write to the container '{container}'. "- "Give the connection string write access to it, then run the sync again."- )+def missing_container_permissions_detail(container: str) -> str:+ # Batch exports' own `MissingRequiredPermissionsError` says "batch export", which reads+ # wrong on a sync. Only the classifier behind it is shared.+ return (+ f"These credentials cannot write to the container '{container}'. "+ "Give the connection string write access to it, then run the sync again."+ )@dataclass(frozen=False, kw_only=True)@@ -176,14 +167,15 @@ class AzureBlobDestinationWriter:name = self._ctx.destination_nameif not self._container:- raise AzureBlobDestinationConfigurationError(- f"Destination {name} has no container. Add a container to the destination, then run the sync again."+ raise DestinationConfigurationError(+ name, "The destination has no container. Add a container to the destination, then run the sync again.")if self._compression not in SUPPORTED_COMPRESSIONS:supported = ", ".join(sorted(SUPPORTED_COMPRESSIONS))- raise AzureBlobDestinationConfigurationError(- f"Destination {name} uses the compression '{self._compression}', which parquet files cannot use. "- f"Pick one of: {supported}."+ raise DestinationConfigurationError(+ name,+ f"The destination uses the compression '{self._compression}', which parquet files cannot use. "+ f"Pick one of: {supported}.",)# --- names ------------------------------------------------------------------------@@ -206,10 +198,14 @@ class AzureBlobDestinationWriter:A writer is built per batch, so a client left open here leaks a session per batch."""+ name = self._ctx.destination_nameif self._ctx.integration_id is None:- raise ValueError(f"Destination {self._ctx.destination_name} has no integration to connect with")+ raise DestinationConfigurationError(name, MISSING_INTEGRATION_DETAIL)- integration = await get_azure_blob_integration(self._ctx.integration_id, self._ctx.team_id)+ try:+ integration = await get_azure_blob_integration(self._ctx.integration_id, self._ctx.team_id)+ except AzureBlobIntegrationNotFoundError as err:+ raise DestinationConfigurationError(name, MISSING_INTEGRATION_DETAIL) from errtry:await asyncio.to_thread(validate_azure_blob_connection_string, integration.connection_string)@@ -221,10 +217,10 @@ class AzureBlobDestinationWriter:retry_policy=ExponentialRetry(initial_backoff=15, increment_base=3, retry_total=3),permit_redirects=False,)- except EndpointNotAllowedError:- raise- except ValueError:- raise MalformedConnectionStringError()+ except EndpointNotAllowedError as err:+ raise DestinationConfigurationError(name, str(err)) from err+ except ValueError as err:+ raise DestinationConfigurationError(name, str(MalformedConnectionStringError())) from errasync with service:yield service.get_container_client(self._container)@@ -234,11 +230,15 @@ class AzureBlobDestinationWriter:blob = container.get_blob_client(name)try:await blob.upload_blob(data, overwrite=True, max_concurrency=self._max_concurrency)- except ResourceNotFoundError:- raise ContainerNotFoundError(self._container)+ except ResourceNotFoundError as err:+ raise DestinationConfigurationError(+ self._ctx.destination_name, container_not_found_detail(self._container)+ ) from errexcept HttpResponseError as err:if is_authorization_failure_response_error(err):- raise MissingContainerPermissionsError(self._container)+ raise DestinationConfigurationError(+ self._ctx.destination_name, missing_container_permissions_detail(self._container)+ ) from errraise# --- writer protocol ----------------------------------------------------------------diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.pyindex bec29759ffdd..2d3b7c485e73 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py@@ -26,10 +26,14 @@ outcome it could not confirm.from __future__ import annotationsimport io+import reimport csvimport json+import socket+import asyncio+import ipaddressfrom collections.abc import AsyncIterator-from contextlib import asynccontextmanager+from contextlib import AsyncExitStack, asynccontextmanagerfrom typing import Any, ClassVarimport psycopg@@ -37,10 +41,12 @@ import pyarrow as pafrom psycopg import sqlfrom posthog.models.integration import Integration, PostgreSQLIntegration+from posthog.psycopg_helpers import has_ipv6_route, is_resolvable_hostname, is_temporary_resolution_failurefrom products.batch_exports.backend.facade.destinations.postgres import (Fields,PostgreSQLClient,+ PostgreSQLConnectionError,PostgreSQLIntegrationNotFoundError,run_in_retryable_transaction,)@@ -50,6 +56,10 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contrDestinationBatchContext,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,)@@ -75,6 +85,110 @@ class UnrelatedTableExistsError(RuntimeError):"""A sync would have replaced or mutated a table this writer never created."""+HOST_RESOLUTION_TIMEOUT_SECONDS = 10++IPV6_ONLY_HOST_DETAIL = (+ "The host has only IPv6 addresses, and PostHog connects to destinations over IPv4. "+ "Use a host name or address that has an IPv4 address, then run the sync again."+)+HOST_NOT_FOUND_DETAIL = "The host name does not exist. Check the host on the destination, then run the sync again."+NETWORK_UNREACHABLE_DETAIL = (+ "PostHog cannot reach the host's network. Check that the host is reachable from the internet over IPv4, "+ "then run the sync again."+)+AUTHENTICATION_FAILED_DETAIL = (+ "The database refused the user name or password. Update the credentials on the destination, "+ "then run the sync again."+)+ACCESS_RULE_DETAIL = (+ "The database does not allow connections from PostHog. Allow PostHog's IP addresses in the database's "+ "access rules, then run the sync again."+)+UNKNOWN_DATABASE_DETAIL = (+ "The database does not exist on this server. Check the database name on the destination, then run the sync again."+)++# Connection failures carry no SQLSTATE: libpq reports them as text only, so these match the+# text. Each one fails the same way on every attempt. A server that sends its messages in another+# language matches none of them, which falls back to the retries, the safe side.+_CONNECT_CONFIGURATION_ERRORS: tuple[tuple[re.Pattern[str], str], ...] = (+ (re.compile(r"Network is unreachable"), NETWORK_UNREACHABLE_DETAIL),+ (re.compile(r"password authentication failed for user"), AUTHENTICATION_FAILED_DETAIL),+ (re.compile(r'role ".*" does not exist'), AUTHENTICATION_FAILED_DETAIL),+ (re.compile(r"no pg_hba\.conf entry for host"), ACCESS_RULE_DETAIL),+ (re.compile(r'database ".*" does not exist'), UNKNOWN_DATABASE_DETAIL),+)++# psycopg tries each address of a host in turn and, when all fail, puts the last attempt's error+# first and then this line before the list of every attempt. Only the last attempt decides: an+# IPv6 address that is unreachable before an IPv4 one that timed out is still a timeout.+_MULTIPLE_ATTEMPTS_LINE = "Multiple connection attempts failed"+++def connect_configuration_error_detail(err: BaseException) -> str | None:+ """What the customer must fix when `err` stops every connection attempt, or None to retry."""+ if isinstance(err, psycopg.errors.ConnectionTimeout):+ return None+ if isinstance(err, psycopg.errors.InvalidPassword | psycopg.errors.InvalidAuthorizationSpecification):+ return AUTHENTICATION_FAILED_DETAIL+ if isinstance(err, psycopg.errors.InvalidCatalogName):+ return UNKNOWN_DATABASE_DETAIL+ if not isinstance(err, psycopg.OperationalError):+ return None++ last_attempt = str(err).split(_MULTIPLE_ATTEMPTS_LINE, 1)[0]+ for pattern, detail in _CONNECT_CONFIGURATION_ERRORS:+ if pattern.search(last_attempt):+ return detail+ return None+++def _is_connect_error_retryable(err: Exception) -> bool:+ return connect_configuration_error_detail(err) is None+++def _is_ipv6(address: str) -> bool:+ try:+ return ipaddress.ip_address(address.strip("[]")).version == 6+ except ValueError:+ return False+++async def _resolve(host: str, port: int) -> list[str]:+ loop = asyncio.get_running_loop()+ infos = await asyncio.wait_for(+ loop.getaddrinfo(host, port, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP),+ timeout=HOST_RESOLUTION_TIMEOUT_SECONDS,+ )+ return [str(info[4][0]) for info in infos]+++async def host_configuration_error_detail(host: str, port: int) -> str | None:+ """What the customer must fix when `host` cannot work from here, or None to go on and connect.++ A lookup that fails on our side (a timeout, an unreachable resolver) returns None, and+ the connect retries handle it. Only an answer about the name itself is the customer's.+ """+ if not host or host.startswith("/"):+ return None++ if is_resolvable_hostname(host):+ try:+ addresses = await _resolve(host, port)+ except TimeoutError:+ return None+ except socket.gaierror as err:+ return None if is_temporary_resolution_failure(err) else HOST_NOT_FOUND_DETAIL+ if not addresses:+ return HOST_NOT_FOUND_DETAIL+ else:+ addresses = [host]++ if all(_is_ipv6(address) for address in addresses) and not has_ipv6_route():+ return IPV6_ONLY_HOST_DETAIL+ return None++# Postgres truncates identifiers past this, dropping the end — which is where our suffixes go.# A long `table_name` would therefore collapse its staging table, merge stage and index back# onto the base name. Truncate the base ourselves so the suffix always survives.@@ -165,21 +279,39 @@ class PostgresDestinationWriter:async def _make_client(self) -> PostgreSQLClient: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)- integration = await self._load_integration(self._ctx.integration_id)+ try:+ integration = await self._load_integration(self._ctx.integration_id)+ except PostgreSQLIntegrationNotFoundError as err:+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL) from errreturn self._client_from_integration(integration)@asynccontextmanagerasync def _client(self) -> AsyncIterator[PostgreSQLClient]:client = await self._make_client()++ # The pre-check resolves the host only to classify it; `connect()` resolves it again.+ host_detail = await host_configuration_error_detail(client.host, client.port)+ if host_detail is not None:+ raise DestinationConfigurationError(self._ctx.destination_name, host_detail)+# `connect()` resolves and dials the integration's hostname with no connection-time# address validation or pinning, same as batch exports' own Postgres destination on# this same client. An editor-controlled hostname could DNS-rebind to a private address# between resolution and connect; closing that needs pinning inside `PostgreSQLClient`# itself (posthog#86986 review discussion), which this product can't reach into, so# every caller of this shared client is fixed together rather than patched here alone.- async with client.connect():+ async with AsyncExitStack() as stack:+ # Entered apart from the body, so only a failure to connect is classified here, never+ # an error the caller raises while it holds the connection.+ try:+ await stack.enter_async_context(client.connect(is_error_retryable=_is_connect_error_retryable))+ except PostgreSQLConnectionError as err:+ detail = connect_configuration_error_detail(err.__cause__) if err.__cause__ else None+ if detail is not None:+ raise DestinationConfigurationError(self._ctx.destination_name, detail) from err+ raiseyield client@asynccontextmanagerdiff --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.pyindex 3429daa12ede..09853622d68f 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@@ -68,6 +68,10 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contrDestinationBatchContext,DestinationRunContext,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ MISSING_INTEGRATION_DETAIL,+ DestinationConfigurationError,+)if TYPE_CHECKING:from types_aiobotocore_s3.client import S3Client@@ -96,10 +100,6 @@ EXPONENTIAL_BACKOFF_COEFFICIENT = ConcurrentS3Consumer.EXPONENTIAL_BACKOFF_COEFFRefreshCredentials = Callable[[], Awaitable[AWSCredentials]]-class S3DestinationConfigurationError(ValueError):- """The destination's config cannot produce a valid S3 write."""--@dataclass(frozen=False, kw_only=True)class _WriteStats:"""What the parquet stream produced, read back after the upload has drained it."""@@ -270,19 +270,21 @@ class S3DestinationWriter:name = self._ctx.destination_nameif not self._bucket:- raise S3DestinationConfigurationError(- f"Destination {name} has no bucket. Add a bucket to the destination, then run the sync again."+ raise DestinationConfigurationError(+ name, "The destination has no bucket. Add a bucket to the destination, then run the sync again.")if not self._region:- raise S3DestinationConfigurationError(- f"Destination {name} has no region. Set the region the bucket is in, for example 'us-east-1', "- "then run the sync again."+ raise DestinationConfigurationError(+ name,+ "The destination has no region. Set the region the bucket is in, for example 'us-east-1', "+ "then run the sync again.",)if self._compression not in SUPPORTED_COMPRESSIONS:supported = ", ".join(sorted(SUPPORTED_COMPRESSIONS))- raise S3DestinationConfigurationError(- f"Destination {name} uses the compression '{self._compression}', which parquet files cannot use. "- f"Pick one of: {supported}."+ raise DestinationConfigurationError(+ name,+ f"The destination uses the compression '{self._compression}', which parquet files cannot use. "+ f"Pick one of: {supported}.",)# --- keys -------------------------------------------------------------------------@@ -306,7 +308,7 @@ class S3DestinationWriter:A writer is built per batch, so a client left open here leaks a session per batch."""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)integration = await get_s3_integration(self._ctx.integration_id, self._ctx.team_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex fbaa116795e1..1c5720bb0828 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -40,6 +40,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineCoalesceMember,extends_set,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DESTINATION_CONFIGURATION_ERROR_MARKER,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessagefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (release_v3_pipeline_lock,@@ -165,6 +168,9 @@ NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (# self-hosted object storage (MinIO) has hit its minimum free drive threshold and is# refusing writes — every retry hits the same full disk until an operator frees space"XMinioStorageFull",+ # a destination's own settings refuse the connection (bad credentials, unknown database,+ # unroutable host); the next scheduled run tries again after the customer fixes them+ DESTINATION_CONFIGURATION_ERROR_MARKER,)# Subset of the non-retryable errors that are expected upstream/customer conditions rather than@@ -178,6 +184,8 @@ EXPECTED_USER_ERROR_PATTERNS: tuple[str, ...] = (# the schema or job was deleted (e.g. the user removed the source) while a batch for it# was still in flight — an upstream/customer action, not a pipeline bug*DELETION_ERROR_PATTERNS,+ # a destination the customer configured refuses the connection, which only they can fix+ DESTINATION_CONFIGURATION_ERROR_MARKER,)# How long an "alive" job-status lookup stays cached before re-checking the app DB.@@ -337,7 +345,9 @@ class DeltaBatchConsumerAdapter:try:# `to_export_signal()` hands back a dict, so it needs parsing the same way the# delivery path does before anything reads a field off it.- await sync_to_async(abort_destinations)(ExportSignalMessage.from_dict(batch.to_export_signal()))+ await sync_to_async(abort_destinations)(+ ExportSignalMessage.from_dict(batch.to_export_signal()), failure_reason=reason+ )except Exception as e:# Best effort by design: a leftover table costs the customer storage, not# correctness, and is not worth failing the fail path over.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex debb61a6bdf8..4db79ade45ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -21,6 +21,10 @@ from products.warehouse_sources.backend.temporal.data_imports.metrics import LOCfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (TransientObjectStoreError,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DestinationConfigurationError,+ DestinationDeliveryError,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue import (consumer as consumer_module,)@@ -211,8 +215,16 @@ class TestProcessSingle:assert states == [SourceBatchStatus.State.EXECUTING, SourceBatchStatus.State.SUCCEEDED]+ @pytest.mark.parametrize(+ "error",+ [+ ValueError("boom"),+ DestinationDeliveryError("Prod", RuntimeError("connection timeout expired")),+ ],+ ids=["generic", "destination_connect_timeout"],+ )@pytest.mark.asyncio- async def test_error_sets_waiting_retry(self):+ async def test_error_sets_waiting_retry(self, error: Exception):consumer = _make_consumer(max_attempts=3)batch = _make_batch(latest_attempt=0)states: list[str] = []@@ -221,7 +233,7 @@ class TestProcessSingle:states.append(job_state)return True- consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))+ consumer._process_batch = AsyncMock(side_effect=error)with patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status_unless_failed",side_effect=track_status,@@ -238,6 +250,7 @@ class TestProcessSingle:"Source column type changed: 'price' has values that no longer fit its stored type int64","[Errno 5] An error occurred (XMinioStorageFull) when calling the CopyObject operation: ""Storage backend has reached its minimum free drive threshold. Please delete a few objects to proceed.",+ str(DestinationConfigurationError("Prod", "The host name does not exist.")),],)@pytest.mark.asyncio@@ -273,6 +286,8 @@ class TestProcessSingle:# upstream/customer condition, not a pipeline bug.("ExternalDataJob matching query does not exist.", False),("ExternalDataSchema matching query does not exist.", False),+ # A destination the customer configured refuses the connection.+ (str(DestinationConfigurationError("Prod", "The host name does not exist.")), False),# A genuine non-retryable failure must still surface so real bugs aren't hidden.("20009.59 is too large to store in a Decimal128 of precision 24.", True),# Storage backend out of disk space is an operational condition operators need to@@ -1720,14 +1735,17 @@ class TestFailRun:),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery.abort_destinations",- side_effect=lambda signal: seen.append(signal),+ side_effect=lambda signal, failure_reason: seen.append((signal, failure_reason)),),):await consumer._fail_run(batch, reason="boom", conn=consumer._poll_conn)assert len(seen) == 1- assert seen[0].destination_ids == ["11111111-1111-1111-1111-111111111111"]- assert seen[0].team_id == 1+ signal, failure_reason = seen[0]+ assert signal.destination_ids == ["11111111-1111-1111-1111-111111111111"]+ assert signal.team_id == 1+ # The abort path reads the reason to skip a destination that failed on its configuration.+ assert failure_reason == "boom"@pytest.mark.asyncioasync def test_attempts_job_status_update_even_when_queue_update_fails(self):