: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-imports): retry the external data job insert on a Postgres deadlock (#82614)
Tom Owers91f460e1f514
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 04823150aa1c..1d122ca2d020 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -27,6 +27,9 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hemit_signals_enabled_for,person_property_sync_enabled_for,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (+ retry_on_operational_error,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (get_v3_pipeline_lock_holder,)@@ -138,6 +141,33 @@ def _build_schema_snapshot(schema: ExternalDataSchema) -> dict[str, Any]:}+@retry_on_operational_error+def _create_job(+ *,+ team_id: int,+ source_id: uuid.UUID,+ schema_id: uuid.UUID,+ pipeline_version: str,+ billable: bool,+ schema_snapshot: dict[str, Any],+) -> ExternalDataJob:+ # A deadlock aborts the INSERT without creating a row, so retrying from scratch is safe. This+ # activity has no Temporal-level retry (see external_data_job.py), because a retry after job+ # creation succeeds would create a duplicate job — retrying just the INSERT avoids that.+ return ExternalDataJob.objects.create(+ team_id=team_id,+ pipeline_id=source_id,+ schema_id=schema_id,+ status=ExternalDataJob.Status.RUNNING,+ rows_synced=0,+ workflow_id=activity.info().workflow_id,+ workflow_run_id=activity.info().workflow_run_id,+ pipeline_version=pipeline_version,+ billable=billable,+ schema_snapshot=schema_snapshot,+ )++# TODO: remove dependency@@ -212,14 +242,10 @@ def create_external_data_job_model_activity(pipeline_version = ExternalDataJob.PipelineVersion.V3_verify_v3_lock_still_held(inputs.team_id, inputs.schema_id)- job = ExternalDataJob.objects.create(+ job = _create_job(team_id=inputs.team_id,- pipeline_id=inputs.source_id,+ source_id=inputs.source_id,schema_id=inputs.schema_id,- status=ExternalDataJob.Status.RUNNING,- rows_synced=0,- workflow_id=activity.info().workflow_id,- workflow_run_id=activity.info().workflow_run_id,pipeline_version=pipeline_version,billable=inputs.billable,schema_snapshot=_build_schema_snapshot(schema),diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex 2d8fe1bf1af8..d2d22c14d22e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -4,6 +4,7 @@ import datetime as dtimport pytestfrom unittest.mock import MagicMock, patch+from django.db import OperationalErrorfrom django.utils import timezonefrom parameterized import parameterized@@ -14,16 +15,19 @@ from posthog.models import Organization, Teamfrom products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotationfrom products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatisticsfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (+ _create_job,_enrichment_pending,_statistics_stale,_verify_v3_lock_still_held,)MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model"+DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"def _team() -> Team:@@ -171,3 +175,46 @@ class TestEnrichmentPending:self._annotate(team, table, "amount")self._annotate(team, table, "")assert _enrichment_pending(team.id, table, _schema(team, table, description=None)) is False+++class TestCreateJob:+ # Guards the deadlock we saw in production: Postgres can abort the ExternalDataJob INSERT with+ # "deadlock detected" while taking its FK lock on posthog_team. The INSERT leaves no row behind,+ # so retrying from scratch is safe — this activity has no Temporal-level retry (a retry after the+ # job row exists would create a duplicate), so the retry has to happen around the INSERT itself.+ @patch(f"{DB_RETRY_MODULE}.close_old_connections")+ @patch(f"{DB_RETRY_MODULE}.time.sleep")+ @patch(f"{MODULE}.activity")+ def test_retries_once_on_deadlock_then_succeeds(+ self, mock_activity: MagicMock, mock_sleep: MagicMock, mock_close_connections: MagicMock+ ) -> None:+ mock_activity.info.return_value.workflow_id = "wf-1"+ mock_activity.info.return_value.workflow_run_id = "run-1"++ team = _team()+ schema = _schema(team, None)+ original_create = ExternalDataJob.objects.create++ def flaky_create(*args: object, **kwargs: object) -> ExternalDataJob:+ flaky_create.calls += 1 # type: ignore[attr-defined]+ if flaky_create.calls == 1: # type: ignore[attr-defined]+ raise OperationalError("deadlock detected")+ return original_create(*args, **kwargs)++ flaky_create.calls = 0 # type: ignore[attr-defined]++ with patch.object(ExternalDataJob.objects, "create", side_effect=flaky_create) as mock_create:+ job = _create_job(+ team_id=team.id,+ source_id=schema.source_id,+ schema_id=schema.id,+ pipeline_version=ExternalDataJob.PipelineVersion.V2,+ billable=True,+ schema_snapshot={},+ )++ assert mock_create.call_count == 2+ assert ExternalDataJob.objects.filter(schema_id=schema.id).count() == 1+ assert job.id is not None+ mock_sleep.assert_called_once()