: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 a stale db connection in property sinks (#88927)
Tom Owers06cf021dffbc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.pyindex 371e1b8039c4..7c8ca7700a6f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py@@ -11,6 +11,7 @@ from pyarrow.parquet import ParquetFile, write_tablefrom structlog.types import FilteringBoundLoggerfrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.utils import aretry_on_db_connection_dropfrom products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (@@ -83,10 +84,16 @@ class AccountPropertyRowSink:async def _get_projection(self) -> list[AccountPropertySourceProjection] | None:"""One projection per enabled account source on the binding (key + mapped columns), or None- when nothing needs staging. Resolved once per run."""+ when nothing needs staging. Resolved once per run.++ The resolver reads the app DB (team scoping, enabled profile sources), so a long-lived+ worker's pooled connection can have gone stale (pooler recycle, failover, deploy) since it+ was last used. Retry once on a fresh connection rather than let that escape as+ error-tracking noise, or as a silently skipped account-property sync for the run.+ """if not self._projection_resolved:- self._projection = await database_sync_to_async_pool(account_property_projection_for)(- self.team_id, self.binding+ self._projection = await aretry_on_db_connection_drop(+ lambda: database_sync_to_async_pool(account_property_projection_for)(self.team_id, self.binding))self._projection_resolved = Truereturn self._projectiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.pyindex 83224a137967..865e4169d77c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py@@ -4,6 +4,7 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings+from django.db import OperationalErrorimport pyarrow as paimport pyarrow.parquet as pq@@ -95,6 +96,24 @@ async def test_stages_only_columns_from_sources_with_a_present_key() -> None:assert to_thread.await_args.args[2].startswith(f"{expected_root}/account_property_sync/7/model_")+async def test_should_run_retries_once_on_a_transient_db_connection_drop() -> None:+ # A long-lived Temporal worker's pooled app-DB connection can go stale (pooler recycle,+ # failover, deploy) between syncs. Without a retry, that one-off OperationalError would+ # propagate and get treated as "no account-property mapping to sync" for the whole run+ # instead of the transient blip it is.+ sink = _sink()+ projection = [+ AccountPropertySourceProjection(key_column="organization_id", columns=frozenset({"organization_id", "mrr"}))+ ]+ resolver = MagicMock(side_effect=[OperationalError("server closed the connection unexpectedly"), projection])++ with patch(f"{_MODULE}.account_property_projection_for", resolver):+ assert await sink.should_run() is True++ assert resolver.call_count == 2++@pytest.mark.asyncioasync def test_stages_an_exact_delta_snapshot_after_materialization() -> None:sink = _sink()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.pyindex 2af7adc58f38..ac1ba431c543 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py@@ -11,6 +11,7 @@ from pyarrow.parquet import write_tablefrom structlog.types import FilteringBoundLoggerfrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.utils import aretry_on_db_connection_dropfrom products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (@@ -105,10 +106,16 @@ class PersonPropertyRowSink:async def _get_projection(self) -> list[PersonPropertySourceProjection] | None:"""One projection per enabled person source on the binding (key + mapped columns), or None- when nothing needs staging. Resolved once per run."""+ when nothing needs staging. Resolved once per run.++ The resolver reads the app DB (team scoping, enabled profile sources), so a long-lived+ worker's pooled connection can have gone stale (pooler recycle, failover, deploy) since it+ was last used. Retry once on a fresh connection rather than let that escape as+ error-tracking noise, or as a silently skipped person-property sync for the run.+ """if not self._projection_resolved:- self._projection = await database_sync_to_async_pool(person_property_projection_for)(- self.team_id, self.binding+ self._projection = await aretry_on_db_connection_drop(+ lambda: database_sync_to_async_pool(person_property_projection_for)(self.team_id, self.binding))self._projection_resolved = Truereturn self._projectiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.pyindex 95ca66c23026..e308e44340b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py@@ -4,6 +4,7 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings+from django.db import OperationalErrorimport pyarrow as pafrom parameterized import parameterized@@ -53,6 +54,22 @@ async def test_should_run_reflects_projection():assert await other.should_run() is True+async def test_should_run_retries_once_on_a_transient_db_connection_drop():+ # A long-lived Temporal worker's pooled app-DB connection can go stale (pooler recycle,+ # failover, deploy) between syncs. Without a retry, that one-off OperationalError would+ # propagate and get treated as "no person-property mapping to sync" for the whole run instead+ # of the transient blip it is.+ sink = _sink()+ projection = [_projection("distinct_id", "plan")]+ resolver = MagicMock(side_effect=[OperationalError("server closed the connection unexpectedly"), projection])++ with patch(f"{_MODULE}.person_property_projection_for", resolver):+ assert await sink.should_run() is True++ assert resolver.call_count == 2++@pytest.mark.asyncioasync def test_stage_chunk_writes_only_projected_columns_present_in_table():sink = _sink()