: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 transient pooler blip on repartition bookkeeping saves (#75747)
Tom Owers527e14880838
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex d60b30cb6d2b..4729c67e6f9f 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -499,9 +499,18 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn Nonedef _save_sync_type_config(self) -> None:+ # temporalio at module scope would put the Temporal client on the django.setup() path —+ # this is a models module (see external_data_source.reload_schemas for the same pattern).+ from posthog.temporal.common.utils import retry_on_db_connection_drop # noqa: PLC0415+# Internal bookkeeping write — skip the activity-log SELECT (see save()) since these run# inside the sync/repartition activity where a dropped pooler connection would fail the run.- self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True)+ # These fire once per batch across every schema sync, so a transient pooler wait_timeout+ # (the pool momentarily out of free backend connections) is worth one retry rather than+ # losing the write silently.+ retry_on_db_connection_drop(+ lambda: self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True)+ )def record_partition_measurement(self, max_partition_bytes: int) -> None:self.sync_type_config["max_partition_bytes"] = max_partition_bytesdiff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 79d5915665ba..5cfc8f799136 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -1,11 +1,12 @@import uuidfrom datetime import date, datetime, timedelta+from typing import Anyimport pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch-from django.db import DatabaseError, transaction+from django.db import DatabaseError, OperationalError, transactionfrom django.db.models import Modelfrom django.test import SimpleTestCasefrom django.utils import timezone@@ -274,6 +275,50 @@ class TestExternalDataSchemaActivityLogging(BaseTest):assert not ExternalDataSchema.objects.filter(pk=schema_id).exists()+class TestSaveSyncTypeConfigRetriesOnConnectionDrop(BaseTest):+ """A pgbouncer `query_wait_timeout` (surfaced as `OperationalError`) on this per-batch+ bookkeeping write used to propagate straight past `record_partition_measurement` and get+ swallowed by the caller's broad except, silently losing the write for that run."""++ def setUp(self) -> None:+ super().setUp()+ self.source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type="Postgres",+ )++ def _create(self, **kwargs) -> ExternalDataSchema:+ return ExternalDataSchema.objects.create(team_id=self.team.pk, source=self.source, name="users", **kwargs)++ def test_retries_once_on_operational_error_then_succeeds(self) -> None:+ schema = self._create()+ real_save = ExternalDataSchema.save+ calls = 0++ def flaky_save(self: ExternalDataSchema, *args: Any, **kwargs: Any) -> None:+ nonlocal calls+ calls += 1+ if calls == 1:+ raise OperationalError("query_wait_timeout")+ real_save(self, *args, **kwargs)++ with patch.object(ExternalDataSchema, "save", flaky_save):+ schema.record_partition_measurement(123)++ assert calls == 2+ schema.refresh_from_db()+ assert schema.sync_type_config["max_partition_bytes"] == 123++ def test_second_consecutive_operational_error_propagates(self) -> None:+ schema = self._create()+ with patch.object(ExternalDataSchema, "save", side_effect=OperationalError("query_wait_timeout")):+ with self.assertRaises(OperationalError):+ schema.record_partition_measurement(123)++class TestExternalDataSchemaOOMEvent(BaseTest):def _source(self) -> ExternalDataSource:return ExternalDataSource.objects.create(