: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): stop reporting queue schema lag as a bug (#102486)
Tom Owerseca73af50caf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 2d654ed9fb44..7b6d79a8ce4d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -112,6 +112,16 @@ def _is_admin_shutdown_error(error: BaseException) -> bool:return isinstance(error, psycopg.errors.AdminShutdown)+# SQLSTATE 42703/42P01: a column or table a sweep query references does not exist yet on the+# queue DB. The migration adding it and the code querying it ship in the same commit, but a+# worker can roll out ahead of the migration completing, so this is a self-healing race, not a+# bug — the sweep already retries every interval, and the query succeeds once the migration+# lands. Mirrors the schema-lag handling in posthog/tasks/alerts/utils.py and+# products/tasks/backend/loop_retention.py.+def _is_schema_lag_error(error: BaseException) -> bool:+ return isinstance(error, psycopg.errors.UndefinedColumn | psycopg.errors.UndefinedTable)++class OwnershipLostError(Exception):"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""@@ -471,8 +481,11 @@ class BatchConsumer:logger.exception(self._event("startup_sweep_error"))capture_exception(e)except Exception as e:- logger.exception(self._event("startup_sweep_error"))- capture_exception(e)+ if _is_schema_lag_error(e):+ logger.warning(self._event("startup_sweep_schema_lag"), error=str(e))+ else:+ logger.exception(self._event("startup_sweep_error"))+ capture_exception(e)self._recovery_task = asyncio.create_task(self._recovery_loop())while not self._shutdown.is_set():@@ -1149,8 +1162,11 @@ class BatchConsumer:logger.exception(self._event("recovery_sweep_error"))capture_exception(e)except Exception as e:- logger.exception(self._event("recovery_sweep_error"))- capture_exception(e)+ if _is_schema_lag_error(e):+ logger.warning(self._event("recovery_sweep_schema_lag"), error=str(e))+ else:+ logger.exception(self._event("recovery_sweep_error"))+ capture_exception(e)now = time.monotonic()if now - self._last_reconcile_monotonic >= self._config.reconcile_interval_seconds: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 999910578fcd..f93ada95c609 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@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_is_admin_shutdown_error,_is_connect_timeout_error,_is_dns_resolution_transient_error,+ _is_schema_lag_error,_is_server_not_ready_error,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState@@ -644,6 +645,43 @@ class TestDnsResolutionTransientErrorClassification:mock_capture.assert_not_called()+class TestSchemaLagErrorClassification:+ def test_classifies_undefined_column_and_table(self) -> None:+ assert _is_schema_lag_error(psycopg.errors.UndefinedColumn("column b.destination_ids does not exist")) is True+ assert _is_schema_lag_error(psycopg.errors.UndefinedTable("relation sourcebatch does not exist")) is True++ def test_ignores_other_programming_errors(self) -> None:+ assert _is_schema_lag_error(psycopg.errors.SyntaxErrorOrAccessRuleViolation("syntax error")) is False++ @pytest.mark.asyncio+ async def test_recovery_loop_does_not_report_schema_lag_error(self):+ # Reproduces the reported issue: a queue-DB migration adding a column and the sweep+ # query reading it ship in the same deploy, but a worker can start polling before the+ # migration finishes applying. The sweep already retries every interval, so this must+ # be treated as self-healing (logged, not sent to error tracking).+ consumer = _make_consumer(recovery_interval_seconds=0.01)+ swept = asyncio.Event()++ async def raise_undefined_column(*args: Any, **kwargs: Any) -> list[PendingBatch]:+ swept.set()+ raise psycopg.errors.UndefinedColumn("column b.destination_ids does not exist")++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",+ side_effect=raise_undefined_column,+ ),+ patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,+ ):+ loop_task = asyncio.create_task(consumer._recovery_loop())+ await asyncio.wait_for(swept.wait(), timeout=2.0)+ consumer._shutdown.set()+ await asyncio.wait_for(loop_task, timeout=5.0)++ mock_capture.assert_not_called()++class TestConnectTimeoutErrorClassification:def test_classifies_connection_timeout(self) -> None:assert _is_connect_timeout_error(psycopg.errors.ConnectionTimeout("connection timeout expired")) is True@@ -1040,10 +1078,11 @@ class TestQueueOperationTimeouts:@pytest.mark.asyncioasync def test_startup_sweep_error_does_not_crash_consumer_and_polling_starts(self):- # Reproduces the reported issue: a schema-level failure (e.g. the queue DB- # missing its tables) during the one-time startup sweep used to propagate out- # of run() uncaught, crashing the consumer -- even though the periodic- # _recovery_loop already tolerates the identical failure from the same call.+ # Reproduces the reported issue: an unexpected failure during the one-time startup+ # sweep used to propagate out of run() uncaught, crashing the consumer -- even+ # though the periodic _recovery_loop already tolerates the identical failure from+ # the same call. Uses a ProgrammingError that isn't schema lag (that case is+ # covered separately and deliberately isn't reported -- see TestSchemaLagErrorClassification).config = ConsumerConfig(database_url="postgres://unused:unused@localhost/unused",poll_interval_seconds=0.01,@@ -1053,7 +1092,7 @@ class TestQueueOperationTimeouts:polling_started = asyncio.Event()async def raise_undefined_table(*args: Any, **kwargs: Any) -> list[PendingBatch]:- raise psycopg.errors.UndefinedTable('relation "sourcebatch" does not exist')+ raise psycopg.errors.SyntaxErrorOrAccessRuleViolation("unexpected sweep failure")async def fetch(*args: Any, **kwargs: Any) -> list[PendingBatch]:polling_started.set()