: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 Postgres write after ClickHouse round-trip drops the connection (#75746)
Tom Owers0ca52d185286
diff --git a/posthog/temporal/tests/common/test_utils.py b/posthog/temporal/tests/common/test_utils.pyindex e52823571b8a..c0758fbb59bd 100644--- a/posthog/temporal/tests/common/test_utils.py+++ b/posthog/temporal/tests/common/test_utils.py@@ -3,7 +3,13 @@ import inspectimport pytestfrom unittest.mock import patch-from posthog.temporal.common.utils import close_db_connections, make_sync_retryable_with_exponential_backoff+from django.db import InterfaceError, OperationalError++from posthog.temporal.common.utils import (+ close_db_connections,+ make_sync_retryable_with_exponential_backoff,+ retry_on_db_connection_drop,+)def test_make_sync_retryable_with_exponential_backoff_called_max_attempts():@@ -189,3 +195,57 @@ def test_close_db_connections_preserves_sync_signature_for_temporal():assert not inspect.iscoroutinefunction(wrapped)assert wrapped.__name__ == "fn"assert wrapped.__annotations__ == {"value": int, "return": str}+++CLOSE_DB_CONNECTIONS_TARGET = "posthog.temporal.common.utils._close_db_connections"+++ "error", [OperationalError("the connection is closed"), InterfaceError("connection already closed")]+)+def test_retry_on_db_connection_drop_retries_once_then_succeeds(error):+ calls = 0++ def operation():+ nonlocal calls+ calls += 1+ if calls == 1:+ raise error+ return "ok"++ with patch(CLOSE_DB_CONNECTIONS_TARGET) as mock_close:+ assert retry_on_db_connection_drop(operation) == "ok"++ assert calls == 2+ mock_close.assert_called_once()+++ "error", [OperationalError("the connection is closed"), InterfaceError("connection already closed")]+)+def test_retry_on_db_connection_drop_raises_after_second_failure(error):+ calls = 0++ def operation():+ nonlocal calls+ calls += 1+ raise error++ with pytest.raises(type(error)):+ retry_on_db_connection_drop(operation)++ assert calls == 2+++def test_retry_on_db_connection_drop_does_not_retry_unrelated_errors():+ calls = 0++ def operation():+ nonlocal calls+ calls += 1+ raise ValueError("not a connection error")++ with pytest.raises(ValueError):+ retry_on_db_connection_drop(operation)++ assert calls == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 119f081875c0..77248b7f4894 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -20,6 +20,7 @@ from clickhouse_driver.errors import ServerExceptionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import retry_on_db_connection_dropfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import (@@ -199,17 +200,20 @@ async def validate_schema_and_update_table(# exhausted the connection pool.table_created: DataWarehouseTable | None = external_data_schema.tableif table_created:- table_created.format = table_params["format"]- table_created.url_pattern = new_url_pattern- table_created.queryable_folder = queryable_folder+ table = table_created+ table.format = table_params["format"]+ table.url_pattern = new_url_pattern+ table.queryable_folder = queryable_folderif external_data_schema.table_row_count_is_cumulative:- table_created.row_count = table_created.get_count()+ table.row_count = table.get_count()else:- table_created.row_count = row_count- # Scope to the fields changed here. This save is now outside the transaction, so a- # full save would rewrite `columns` with its pre-merge value and could clobber a- # concurrent sync's column update before the select_for_update merge below runs.- table_created.save(update_fields=["format", "url_pattern", "queryable_folder", "row_count"])+ table.row_count = row_count+ # get_count() above can retry against a degraded ClickHouse cluster for minutes, long+ # enough for the pooled Postgres connection to be recycled underneath us. Retry once+ # on a fresh connection rather than let this escape as error-tracking noise.+ retry_on_db_connection_drop(+ lambda: table.save(update_fields=["format", "url_pattern", "queryable_folder", "row_count"])+ )if not table_created:# Check if we already have an orphaned table that we can repurpose@@ -234,40 +238,47 @@ async def validate_schema_and_update_table(raw_db_columns = table_created.get_columns()db_columns = {key: str(column.get("clickhouse", "")) for key, column in raw_db_columns.items()}- with transaction.atomic():- # select_for_update prevents two concurrent sync operations from- # causing a lost-update: both would read the current columns,- # merge independently, and one write would overwrite the other.- # Use raw_objects to skip the default manager's select_related —- # its nullable LEFT JOINs are rejected by Postgres under FOR UPDATE.- table_for_update = DataWarehouseTable.raw_objects.select_for_update().get(id=table_created.id)- existing_columns = table_for_update.columns or {}- columns = merge_columns(db_columns, table_schema_dict or {}, existing_columns)- # Project to enabled_columns so disabled columns the user already deselected don't- # creep back into HogQL via the Delta schema (which still contains them historically).- # Prefer source-detected PKs (always present) over the schema model's PKs (only set- # for CDC and user-picked incremental keys) so non-CDC schemas don't drop their PKs.- effective_primary_keys = primary_keys or external_data_schema.primary_key_columns- columns = filter_dwh_columns_by_enabled_columns(- columns,- external_data_schema.enabled_columns,- effective_primary_keys,- external_data_schema.incremental_field,- )- table_for_update.columns = columns- table_for_update.save(update_fields=["columns"])- # Keep local reference in sync- table_created.columns = columns-- # schema could have been deleted by this point- schema_model = (- ExternalDataSchema.objects.prefetch_related("source")- .exclude(deleted=True)- .get(id=_schema_id, team_id=team_id)- )+ def _persist_columns() -> None:+ with transaction.atomic():+ # select_for_update prevents two concurrent sync operations from+ # causing a lost-update: both would read the current columns,+ # merge independently, and one write would overwrite the other.+ # Use raw_objects to skip the default manager's select_related —+ # its nullable LEFT JOINs are rejected by Postgres under FOR UPDATE.+ table_for_update = DataWarehouseTable.raw_objects.select_for_update().get(id=table_created.id)+ existing_columns = table_for_update.columns or {}+ columns = merge_columns(db_columns, table_schema_dict or {}, existing_columns)+ # Project to enabled_columns so disabled columns the user already deselected don't+ # creep back into HogQL via the Delta schema (which still contains them historically).+ # Prefer source-detected PKs (always present) over the schema model's PKs (only set+ # for CDC and user-picked incremental keys) so non-CDC schemas don't drop their PKs.+ effective_primary_keys = primary_keys or external_data_schema.primary_key_columns+ columns = filter_dwh_columns_by_enabled_columns(+ columns,+ external_data_schema.enabled_columns,+ effective_primary_keys,+ external_data_schema.incremental_field,+ )+ table_for_update.columns = columns+ table_for_update.save(update_fields=["columns"])+ # Keep local reference in sync+ table_created.columns = columns++ # schema could have been deleted by this point+ schema_model = (+ ExternalDataSchema.objects.prefetch_related("source")+ .exclude(deleted=True)+ .get(id=_schema_id, team_id=team_id)+ )++ schema_model.table = table_created+ schema_model.save()- schema_model.table = table_created- schema_model.save()+ # get_columns() above retries against ClickHouse the same way and can also block for+ # minutes, long enough for the pooled connection used by select_for_update() below to go+ # stale. A dropped connection mid-atomic-block rolls the block back, so retrying it whole+ # is safe.+ retry_on_db_connection_drop(_persist_columns)except ServerException as err:if err.code == 636:@@ -347,13 +358,19 @@ async def register_cdc_companion_table().first()if companion_table:- companion_table.format = table_format- companion_table.url_pattern = new_url_pattern- companion_table.queryable_folder = queryable_folder- companion_table.row_count = companion_table.get_count()+ table = companion_table+ table.format = table_format+ table.url_pattern = new_url_pattern+ table.queryable_folder = queryable_folder+ table.row_count = table.get_count()# Scope to the fields changed here so this out-of-transaction save doesn't rewrite# `columns` with its pre-merge value before the column save below.- companion_table.save(update_fields=["format", "url_pattern", "queryable_folder", "row_count"])+ # get_count() above can retry against a degraded ClickHouse cluster for minutes, long+ # enough for the pooled Postgres connection to be recycled underneath us. Retry once+ # on a fresh connection rather than let this escape as error-tracking noise.+ retry_on_db_connection_drop(+ lambda: table.save(update_fields=["format", "url_pattern", "queryable_folder", "row_count"])+ )else:logger.debug(f"Creating CDC companion table: {companion_table_name}")companion_table = DataWarehouseTable.objects.create(@@ -365,12 +382,18 @@ async def register_cdc_companion_table(existing_columns = companion_table.columns or {}columns = merge_columns(db_columns, table_schema_dict or {}, existing_columns)- with transaction.atomic():- companion_table.columns = columns- companion_table.save(update_fields=["columns"])+ def _persist_columns() -> None:+ with transaction.atomic():+ companion_table.columns = columns+ companion_table.save(update_fields=["columns"])++ if set_as_schema_table:+ ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id).update(table=companion_table)- if set_as_schema_table:- ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id).update(table=companion_table)+ # get_columns() above retries against ClickHouse the same way and can also block for+ # minutes, long enough for the pooled connection to go stale. A dropped connection rolls+ # the atomic block back, so retrying it whole is safe.+ retry_on_db_connection_drop(_persist_columns)except Exception as e:logger.exception(