: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(warehouse-sources): disable schemas on permanent v3 load failures (#91891)
Daniel RC1926acc83930
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex c2482864508d..4b6de10d9db7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -23,6 +23,7 @@ from asgiref.sync import sync_to_asyncfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.db_errors import is_transient_db_error+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, update_should_syncfrom products.warehouse_sources.backend.temporal.data_imports.metrics import (LOCK_TAKEOVER_LATEST_ERROR,TERMINAL_JOB_STATUSES,@@ -83,9 +84,11 @@ STRANDED_RUN_ERROR = ("The next scheduled sync retries automatically. No action is needed.")-# Errors that fail identically on every attempt. Substring-matched because they-# surface as generic exceptions; keep entries specific so transients can't match.-NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (++# Permanent failures the customer can fix. These stop the schedule as well as the run: the loader+# fails outside the workflow, so the finalization activity that would otherwise disable the schema+# never runs, and every later run replays the same failure.+DISABLE_SCHEMA_ERROR_PATTERNS: tuple[str, ...] = (# delta-rs decimal precision overflow — the batch's data cannot fit the column"is too large to store in a Decimal128",# schema configured as incremental without a primary key — config error@@ -93,6 +96,14 @@ NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (# incoming values no longer fit the stored Delta column type# (SchemaColumnTypeChangedException) — only a reset and full re-sync can fix it"Source column type changed",+)++# Errors that fail identically on every attempt. Substring-matched because they+# surface as generic exceptions; keep entries specific so transients can't match.+# The disable set above, plus the permanent failures that must not stop the schedule: a deleted row+# has nothing left to disable, and a full object store is an infrastructure fix, not a sync setting.+NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (+ *DISABLE_SCHEMA_ERROR_PATTERNS,# the schema or job row was deleted mid-sync — no retry can bring it back"ExternalDataSchema matching query does not exist","ExternalDataJob matching query does not exist",@@ -252,6 +263,19 @@ class DeltaBatchConsumerAdapter:logger.exception("fail_run_job_status_update_failed", job_id=batch.job_id, run_uuid=batch.run_uuid)capture_exception(e)+ if any(pattern in reason for pattern in DISABLE_SCHEMA_ERROR_PATTERNS):+ try:+ await sync_to_async(_disable_schema_after_permanent_failure)(+ schema_id=batch.schema_id,+ team_id=batch.team_id,+ reason=reason,+ )+ except Exception as e:+ # The run is already failed and the message recorded; a failed disable only means+ # the next run retries, so log it rather than crashing the consumer.+ logger.exception("fail_run_disable_schema_failed", schema_id=batch.schema_id, run_uuid=batch.run_uuid)+ capture_exception(e)+workflow_run_id = batch.metadata.get("workflow_run_id")if workflow_run_id:try:@@ -739,6 +763,24 @@ def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> Nopass+def _disable_schema_after_permanent_failure(*, schema_id: str, team_id: int, reason: str) -> bool:+ """Stop a schema whose load failed permanently. Returns whether it flipped.++ Reads ``should_sync`` first so a run whose batches fail one after another pauses the Temporal+ schedule once instead of per batch, and so a schema deleted mid-run is skipped rather than+ raising out of ``update_should_sync``'s ``get``.+ """+ close_old_connections()++ schema = ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id).only("id", "should_sync").first()+ if schema is None or not schema.should_sync:+ return False++ update_should_sync(schema_id=schema_id, team_id=team_id, should_sync=False, disable_error_message=reason)+ logger.warning("fail_run_disabled_schema", schema_id=schema_id, reason=reason)+ return True++def mark_job_failed_if_not_terminal(*, job_id: str, team_id: int, error: str) -> bool:"""Mark a non-terminal ExternalDataJob Failed; returns True if it transitioned (terminal jobs are a no-op).diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 003fb93cf09d..f210930944ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -1383,6 +1383,60 @@ class TestPollBackoff:class TestFailRun:+ MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"++ @pytest.mark.parametrize(+ ("reason", "expect_disabled"),+ [+ pytest.param(+ "Source column type changed: 'total_cost' has values that no longer fit its stored type int64",+ True,+ id="column_type_changed",+ ),+ pytest.param("Decimal value is too large to store in a Decimal128", True, id="decimal_overflow"),+ pytest.param("Primary key required for incremental syncs", True, id="missing_primary_key"),+ pytest.param(+ "XMinioStorageFull: storage backend has reached its minimum free drive threshold",+ False,+ id="our_storage_full",+ ),+ pytest.param("ExternalDataSchema matching query does not exist", False, id="schema_deleted"),+ pytest.param("ExternalDataJob matching query does not exist", False, id="job_deleted"),+ pytest.param("max retries exceeded: the connection is closed", False, id="transient_exhausted"),+ ],+ )+ @pytest.mark.asyncio+ async def test_only_customer_fixable_failures_disable_the_schema(self, reason, expect_disabled):+ consumer = _make_consumer()+ batch = _make_batch()++ with (+ patch(f"{self.MODULE}.BatchQueue.fail_run", new_callable=AsyncMock),+ patch(f"{self.MODULE}._update_job_status_to_failed"),+ patch(f"{self.MODULE}._disable_schema_after_permanent_failure") as mock_disable,+ ):+ await consumer._fail_run(batch, reason=reason, conn=consumer._poll_conn)++ assert mock_disable.called is expect_disabled++ @pytest.mark.asyncio+ async def test_disable_failure_does_not_crash_the_consumer(self):+ consumer = _make_consumer()+ batch = _make_batch()++ with (+ patch(f"{self.MODULE}.BatchQueue.fail_run", new_callable=AsyncMock),+ patch(f"{self.MODULE}._update_job_status_to_failed"),+ patch(+ f"{self.MODULE}._disable_schema_after_permanent_failure",+ side_effect=Exception("the connection is closed"),+ ),+ patch(f"{self.MODULE}.capture_exception") as mock_capture,+ ):+ await consumer._fail_run(batch, reason="Source column type changed: 'x'", conn=consumer._poll_conn)++ mock_capture.assert_called_once()+@pytest.mark.asyncioasync def test_does_not_raise_when_job_status_update_fails(self):# A dropped app-DB connection while marking the job Failed must not propagate out of _fail_run.