: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): handle non-retryable errors raised during source setup (#63812)
Tom Owersad0b6ceaf697
diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.pyindex 16e500792e72..a1252fa57619 100644--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py@@ -2,7 +2,7 @@ import uuidimport asyncioimport datetime as dtimport dataclasses-from typing import Any, Optional+from typing import Any, NoReturn, Optionalfrom django.db.models import Prefetch@@ -207,6 +207,14 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelinconsumer_manages_job_status=True,skip_post_import_activities=True,)+ except Exception as e:+ # Some sources connect to the remote during setup rather than lazily during+ # the run — e.g. for a `mongodb+srv://` URI pymongo resolves the SRV DNS+ # record inside the MongoClient constructor. A non-retryable error raised+ # here (deleted/misconfigured cluster hostname, revoked credentials) would+ # otherwise bypass the guard in `_run` and be retried up to the activity's+ # maximum on every scheduled sync. Route it through the same policy.+ await _handle_import_error(job_inputs, logger, e)return await _run(job_inputs=job_inputs,@@ -236,6 +244,33 @@ def _get_models(return job, schema, source, table+async def _handle_import_error(+ job_inputs: PipelineInputs,+ logger: FilteringBoundLogger,+ error: Exception,+) -> NoReturn:+ """Route an import error through the source's non-retryable error policy.++ Errors the source classifies as non-retryable (bad credentials, a deleted or+ misconfigured remote — e.g. a MongoDB ``mongodb+srv://`` hostname whose DNS record no+ longer resolves) are handed to ``handle_non_retryable_error``, which stops the job after+ a few attempts instead of retrying up to the activity's maximum. Everything else is+ re-raised so Temporal retries it as usual.+ """+ source_cls = SourceRegistry.get_source(job_inputs.job_type)+ non_retryable_errors = source_cls.get_non_retryable_errors()+ error_msg = str(error)+ is_non_retryable_error = any(+ non_retryable_error in error_msg for non_retryable_error in non_retryable_errors.keys()+ )+ if is_non_retryable_error:+ await handle_non_retryable_error(job_inputs, error_msg, logger, error)+ else:+ await logger.aexception(error_msg)+ await logger.adebug("Error encountered during import_data_activity - re-raising")+ raise error++async def _run(job_inputs: PipelineInputs,source_response: SourceResponse,@@ -284,15 +319,4 @@ async def _run(await logger.adebug("Finished running pipeline")return resultexcept Exception as e:- source_cls = SourceRegistry.get_source(job_inputs.job_type)- non_retryable_errors = source_cls.get_non_retryable_errors()- error_msg = str(e)- is_non_retryable_error = any(- non_retryable_error in error_msg for non_retryable_error in non_retryable_errors.keys()- )- if is_non_retryable_error:- await handle_non_retryable_error(job_inputs, error_msg, logger, e)- else:- await logger.aexception(error_msg)- await logger.adebug("Error encountered during import_data_activity - re-raising")- raise+ await _handle_import_error(job_inputs, logger, e)diff --git a/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pynew file mode 100644index 000000000000..cc10be68adf9--- /dev/null+++ b/posthog/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -0,0 +1,108 @@+import uuid+import contextlib++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.common.base import SimpleSource+from posthog.temporal.data_imports.util import NonRetryableException+from posthog.temporal.data_imports.workflow_activities import import_data_sync as module+from posthog.temporal.data_imports.workflow_activities.import_data_sync import (+ ImportDataActivityInputs,+ import_data_activity_sync,+)+++class _FakeAsyncCM:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False+++def _passthrough(fn):+ """Stand-in for database_sync_to_async_pool that just calls the wrapped fn."""++ async def _inner(*args, **kwargs):+ return fn(*args, **kwargs)++ return _inner+++def _patched_activity(source_mock):+ """Patch out every dependency import_data_activity_sync touches before source setup."""+ model = mock.MagicMock()+ model.pipeline.source_type = "MongoDB"+ model.pipeline.job_inputs = {}+ model.folder_path = mock.Mock(return_value="dataset")++ schema = mock.MagicMock()+ schema.should_use_incremental_field = False++ with (+ mock.patch.object(module, "tag_queries"),+ mock.patch.object(module, "report_heartbeat_timeout"),+ mock.patch.object(module, "Heartbeater", return_value=_FakeAsyncCM()),+ mock.patch.object(module, "ShutdownMonitor", return_value=_FakeAsyncCM()),+ mock.patch.object(module, "setup_row_tracking", new=mock.AsyncMock()),+ mock.patch.object(module, "_get_external_data_job", new=mock.AsyncMock(return_value=model)),+ mock.patch.object(module, "_get_external_data_schema", new=mock.AsyncMock(return_value=schema)),+ mock.patch.object(module, "ExternalDataSourceType", return_value="MongoDB"),+ mock.patch.object(module, "bind_job_context"),+ mock.patch.object(module, "trim_source_job_inputs", new=mock.AsyncMock()),+ mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),+ mock.patch.object(module.SourceRegistry, "is_registered", return_value=True),+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source_mock),+ mock.patch.object(module, "handle_non_retryable_error", new=mock.AsyncMock()) as handle_mock,+ ):+ yield handle_mock+++def _make_source(error: Exception, non_retryable: dict[str, str | None]):+ source = mock.MagicMock(spec=SimpleSource)+ source.parse_config.return_value = {}+ source.get_non_retryable_errors.return_value = non_retryable+ source.source_for_pipeline.side_effect = error+ return source+++def _inputs() -> ImportDataActivityInputs:+ return ImportDataActivityInputs(+ team_id=1,+ schema_id=uuid.uuid4(),+ source_id=uuid.uuid4(),+ run_id=str(uuid.uuid4()),+ reset_pipeline=True,+ )+++async def test_non_retryable_setup_error_routes_through_handler():+ # A MongoDB mongodb+srv:// URI resolves DNS in the MongoClient constructor, so a deleted+ # cluster hostname raises during source setup (source_for_pipeline), before the run phase.+ error = Exception("The DNS query name does not exist: _mongodb._tcp.cluster0.example.mongodb.net.")+ source = _make_source(error, {"The DNS query name does not exist": None})++ with _patched_activity(source) as handle_mock:+ # handle_non_retryable_error always raises (re-raises the error, or NonRetryableException+ # once retries are exhausted) — mirror that so the activity doesn't fall through to _run.+ handle_mock.side_effect = NonRetryableException()+ with pytest.raises(NonRetryableException):+ await import_data_activity_sync(_inputs())++ handle_mock.assert_awaited_once()+ assert handle_mock.await_args.args[3] is error+++async def test_retryable_setup_error_is_reraised():+ error = Exception("connection reset by peer")+ source = _make_source(error, {"The DNS query name does not exist": None})++ with _patched_activity(source) as handle_mock:+ with pytest.raises(Exception, match="connection reset by peer"):+ await import_data_activity_sync(_inputs())++ handle_mock.assert_not_awaited()