: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): stop endless retries on an unsupported schema sync type (#113185)
Tom Owers351d99fe5e17
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex dae771557d40..5a2325438512 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -23,6 +23,10 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+class UnsupportedSyncTypeError(ValueError):+ """The stored sync type is not a mode PostHog can run."""++@dataclass(frozen=True)class RevenueViewSyncInput:team_id: intdiff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.pyindex 8a70f4d19e50..f5acddfd4bac 100644--- a/products/warehouse_sources/backend/facade/models.py+++ b/products/warehouse_sources/backend/facade/models.py@@ -12,6 +12,7 @@ at ``django.setup()``.Consumers that only read fields should use ``facade.api`` (contracts) instead."""+from products.warehouse_sources.backend.facade.contracts import UnsupportedSyncTypeErrorfrom 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 (@@ -40,6 +41,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (get_all_schemas_for_source_id,get_schemas_for_direct_reconciliation,mark_schema_running_unless_halted,+ resolve_sync_type,sync_frequency_interval_to_sync_frequency,sync_frequency_to_sync_frequency_interval,sync_old_schemas_with_new_schemas,@@ -135,6 +137,8 @@ __all__ = ["update_should_sync","mark_schema_running_unless_halted","update_sync_type_config_keys",+ "UnsupportedSyncTypeError",+ "resolve_sync_type","CDC_SNAPSHOT_LANE_KEY","validate_source_prefix","validate_warehouse_table_url_pattern",diff --git a/products/warehouse_sources/backend/migrations/0173_repair_legacy_full_sync_type.py b/products/warehouse_sources/backend/migrations/0173_repair_legacy_full_sync_type.pynew file mode 100644index 000000000000..b1210549915e--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0173_repair_legacy_full_sync_type.py@@ -0,0 +1,18 @@+from django.db import migrations+++def repair_legacy_full_sync_type(apps, schema_editor):+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")+ # `_base_manager` so soft-deleted rows are repaired too: an undelete would otherwise+ # bring the unusable value back.+ ExternalDataSchema._base_manager.filter(sync_type="full").update(sync_type="full_refresh")+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0172_migrate_apple_search_ads_job_inputs_to_auth_method"),+ ]++ operations = [+ migrations.RunPython(repair_legacy_full_sync_type, migrations.RunPython.noop),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex d50e841ea32f..403d85f71b17 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0172_migrate_apple_search_ads_job_inputs_to_auth_method+0173_repair_legacy_full_sync_typediff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 938aa6eaf347..4dfee057ff37 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -25,6 +25,7 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom posthog.sync import database_sync_to_async+from products.warehouse_sources.backend.facade.contracts import UnsupportedSyncTypeErrorfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.retry_limits import (MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION,@@ -50,6 +51,32 @@ logger = structlog.get_logger(__name__)type IncrementalFieldValue = str | int | float | None+# Sync type strings that early clients wrote to the column. They name a real mode, so they map to it.+LEGACY_SYNC_TYPE_ALIASES: dict[str, ExternalDataSchemaSyncType] = {+ "full": ExternalDataSchemaSyncType.FULL_REFRESH,+}++# Matched by `Any_Source_Errors`, so the exception text must keep this prefix.+UNSUPPORTED_SYNC_TYPE_ERROR = "Unsupported sync type"+UNSUPPORTED_SYNC_TYPE_DISABLED_MESSAGE = (+ "This table has a sync type that PostHog does not support. Choose a sync type in the table's "+ "sync settings, then re-enable the sync."+)+++def resolve_sync_type(value: str | None) -> ExternalDataSchemaSyncType | None:+ """Turn a stored `sync_type` into the enum. The column does not enforce its choices."""+ if value is None:+ return None+ try:+ return ExternalDataSchemaSyncType(value)+ except ValueError:+ alias = LEGACY_SYNC_TYPE_ALIASES.get(value)+ if alias is not None:+ return alias+ raise UnsupportedSyncTypeError(f"{UNSUPPORTED_SYNC_TYPE_ERROR}: '{value}'") from None++# Recorded as the job's latest_error, which the syncs UI shows to the customer.SYNC_DISABLED_JOB_ERROR = "Sync stopped because syncing was turned off"SCHEMA_DELETED_JOB_ERROR = "Sync stopped because the table was deleted"diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex bd98bfe36ce4..30715c25732e 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -50,8 +50,10 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSchema,ExternalDataSchemaDestination,ExternalDataSource,+ UnsupportedSyncTypeError,mark_schema_running_unless_halted,resolve_destinations,+ resolve_sync_type,sync_frequency_interval_to_sync_frequency,sync_frequency_to_sync_frequency_interval,update_sync_type_config_keys,@@ -771,7 +773,11 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersdef to_representation(self, instance: ExternalDataSchema) -> dict:ret = super().to_representation(instance)- ret["sync_type"] = ExternalDataSchema.SyncType(instance.sync_type) if instance.sync_type is not None else None+ try:+ ret["sync_type"] = resolve_sync_type(instance.sync_type)+ except UnsupportedSyncTypeError:+ # Returning None keeps the list and settings pages loading so the user can pick a valid type.+ ret["sync_type"] = Noneret["sync_frequency"] = sync_frequency_interval_to_sync_frequency(instance.sync_frequency_interval)ret["sync_time_of_day"] = (self.fields["sync_time_of_day"].to_representation(instance.sync_time_of_day)diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 54dd7e0b3f5a..988dd8de22c2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -48,6 +48,8 @@ from products.warehouse_sources.backend.models.external_data_schema import (AUTO_DISABLED_JOB_ERROR,DUPLICATE_PRIMARY_KEY_DISABLED_MESSAGE,MISSING_PRIMARY_KEY_DISABLED_MESSAGE,+ UNSUPPORTED_SYNC_TYPE_DISABLED_MESSAGE,+ UNSUPPORTED_SYNC_TYPE_ERROR,ExternalDataSchema,update_should_sync,)@@ -189,6 +191,7 @@ Any_Source_Errors: dict[str, str | None] = {"configuration, then re-enable the sync."),MISSING_PRIMARY_KEYS_ERROR: MISSING_PRIMARY_KEY_DISABLED_MESSAGE,+ UNSUPPORTED_SYNC_TYPE_ERROR: UNSUPPORTED_SYNC_TYPE_DISABLED_MESSAGE,DUPLICATE_PRIMARY_KEYS_ERROR: DUPLICATE_PRIMARY_KEY_DISABLED_MESSAGE,"Integration matching query does not exist": MISSING_INTEGRATION_MESSAGE,# `OAuthMixin.get_oauth_integration` catches `Integration.DoesNotExist` and re-raises thesediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex 650b81993aee..d8e5ca17eaf3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -34,9 +34,11 @@ from posthog.temporal.common.utils import is_stale_connection_read_only_errorfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,+ UnsupportedSyncTypeError,apply_incremental_lookback,get_schema_if_exists,process_incremental_value,+ resolve_sync_type,staged_handoff_resume_point,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -592,9 +594,16 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:new_source, schema.sync_type_config if use_stored_cursors else None, logger)+ try:+ resolved_sync_type = resolve_sync_type(schema.sync_type)+ except UnsupportedSyncTypeError as e:+ await handle_non_retryable_error(+ job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, str(e), logger, e+ )+source_inputs = SourceInputs(schema_name=schema.name,- sync_type=ExternalDataSchema.SyncType(schema.sync_type) if schema.sync_type is not None else None,+ sync_type=resolved_sync_type,schema_id=str(schema.id),source_id=str(inputs.source_id),team_id=inputs.team_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 6fa1bd6d1646..64c99a6262be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -1263,6 +1263,7 @@ def _probe_model() -> mock.MagicMock:def _probe_schema() -> mock.MagicMock:schema = mock.MagicMock()schema.id = uuid.uuid4()+ schema.sync_type = ExternalDataSchema.SyncType.FULL_REFRESHschema.should_use_incremental_field = Falseschema.is_incremental = Falseschema.sync_type_config = {}diff --git a/products/warehouse_sources/backend/tests/test_resolve_sync_type.py b/products/warehouse_sources/backend/tests/test_resolve_sync_type.pynew file mode 100644index 000000000000..6a6ee646117c--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_resolve_sync_type.py@@ -0,0 +1,34 @@+import pytest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.warehouse_sources.backend.models.external_data_schema import (+ UNSUPPORTED_SYNC_TYPE_ERROR,+ ExternalDataSchema,+ UnsupportedSyncTypeError,+ resolve_sync_type,+)+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+++class TestResolveSyncType(SimpleTestCase):+ @parameterized.expand(+ [+ ("none", None, None),+ ("full_refresh", "full_refresh", ExternalDataSchema.SyncType.FULL_REFRESH),+ ("incremental", "incremental", ExternalDataSchema.SyncType.INCREMENTAL),+ ("legacy_full", "full", ExternalDataSchema.SyncType.FULL_REFRESH),+ ]+ )+ def test_resolves(self, _name, stored, expected):+ assert resolve_sync_type(stored) == expected++ @parameterized.expand([("unknown", "bogus"), ("wrong_case", "Full"), ("empty", "")])+ def test_unsupported_value_raises_error_that_disables_the_schema(self, _name, stored):+ with pytest.raises(UnsupportedSyncTypeError) as exc_info:+ resolve_sync_type(stored)++ assert any(marker in str(exc_info.value) for marker in Any_Source_Errors)+ assert str(exc_info.value).startswith(UNSUPPORTED_SYNC_TYPE_ERROR)