: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 sync queue outages disabling source schemas (#112479)
Tom Owers9f343e4853cf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.pyindex a22d083f6dde..2a8bec7ec0f5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py@@ -10,6 +10,8 @@ from __future__ import annotationsimport jsonimport time+from collections.abc import Iterator+from contextlib import contextmanagerfrom typing import Any, Optionalimport psycopg@@ -22,6 +24,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typPartitionFormat,PartitionMode,)+from products.warehouse_sources.backend.temporal.data_imports.util import (+ PostHogInternalDatabaseError,+ is_transient_internal_db_error,+)from products.warehouse_sources_queue.backend.core.jobs_db import BATCH_TABLE, BatchQueuelogger = structlog.get_logger(__name__)@@ -43,6 +49,19 @@ def _connect_with_retry(database_url: str) -> psycopg.Connection:return psycopg.Connection.connect(database_url, autocommit=True)+@contextmanager+def _queue_db_errors() -> Iterator[None]:+ # The queue lives in PostHog's own database, but a raw psycopg error from it reads exactly like+ # one from a customer's Postgres source. The source's non-retryable errors would then match it+ # and disable a healthy schema, telling the customer to fix a database that is working.+ try:+ yield+ except psycopg.Error as e:+ if is_transient_internal_db_error(e):+ raise PostHogInternalDatabaseError("Failed to reach PostHog's sync queue database") from e+ raise++class PostgresProducer:"""Writes batch rows directly into the Postgres queue on each send call."""@@ -100,7 +119,8 @@ class PostgresProducer:None if external_destination_ids is None else list(external_destination_ids))- self._conn = _connect_with_retry(database_url)+ with _queue_db_errors():+ self._conn = _connect_with_retry(database_url)self._batches_sent = 0# The most recent staged batch and its cumulative row count, kept out of the queue until the# next batch arrives or the run ends, so the run's last row can carry the final flag itself.@@ -211,12 +231,13 @@ class PostgresProducer:# A full_refresh is the exception: this run's batch 0 overwrites the table, so# an older attempt's loaded rows are gone either way and sparing it only leaves# its batches clogging the serial per-(team, schema) gate.- superseded = BatchQueue.supersede_other_runs(- self._conn,- job_id=self._job_id,- current_run_uuid=self._run_uuid,- spare_runs_with_progress=self._sync_type != "full_refresh",- )+ with _queue_db_errors():+ superseded = BatchQueue.supersede_other_runs(+ self._conn,+ job_id=self._job_id,+ current_run_uuid=self._run_uuid,+ spare_runs_with_progress=self._sync_type != "full_refresh",+ )if superseded > 0:self._logger.info("superseded_old_run_batches", count=superseded)@@ -262,8 +283,9 @@ class PostgresProducer:if self._external_destination_ids is not None:metadata["external_destination_ids"] = self._external_destination_ids- self._conn.execute(- f"""+ with _queue_db_errors():+ self._conn.execute(+ f"""INSERT INTO {BATCH_TABLE} (team_id, schema_id, source_id, job_id, run_uuid,batch_index, s3_path, row_count, byte_size, is_final_batch,@@ -275,29 +297,29 @@ class PostgresProducer:%(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,%(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, %(destination_ids)s, now())- """,- {- "team_id": self._team_id,- "schema_id": self._schema_id,- "source_id": self._source_id,- "job_id": self._job_id,- "run_uuid": self._run_uuid,- "batch_index": batch_result.batch_index,- "s3_path": batch_result.s3_path,- "row_count": batch_result.row_count,- "byte_size": batch_result.byte_size,- "is_final_batch": is_final_batch,- "total_batches": total_batches,- "total_rows": total_rows,- "sync_type": self._sync_type,- "cumulative_row_count": cumulative_row_count,- "resource_name": self._resource_name,- "is_resume": self._is_resume,- "is_first_ever_sync": self._is_first_ever_sync,- "metadata": json.dumps(metadata),- "destination_ids": json.dumps(self._destination_ids),- },- )+ """,+ {+ "team_id": self._team_id,+ "schema_id": self._schema_id,+ "source_id": self._source_id,+ "job_id": self._job_id,+ "run_uuid": self._run_uuid,+ "batch_index": batch_result.batch_index,+ "s3_path": batch_result.s3_path,+ "row_count": batch_result.row_count,+ "byte_size": batch_result.byte_size,+ "is_final_batch": is_final_batch,+ "total_batches": total_batches,+ "total_rows": total_rows,+ "sync_type": self._sync_type,+ "cumulative_row_count": cumulative_row_count,+ "resource_name": self._resource_name,+ "is_resume": self._is_resume,+ "is_first_ever_sync": self._is_first_ever_sync,+ "metadata": json.dumps(metadata),+ "destination_ids": json.dumps(self._destination_ids),+ },+ )self._batches_sent += 1if is_final_batch:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.pyindex b19cf64d81b2..c8c5fad14b02 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinePostgresProducer,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult+from products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseErrordef _default_kwargs(**kwargs: Any) -> dict[str, Any]:@@ -78,7 +79,7 @@ class TestPostgresProducerConnectRetry:) as mock_connect,patch(self._SLEEP_TARGET),):- with pytest.raises(psycopg.OperationalError):+ with pytest.raises(PostHogInternalDatabaseError):PostgresProducer(**_default_kwargs())assert mock_connect.call_count == 3@@ -221,6 +222,32 @@ class TestPostgresProducerSupersede:mock_supersede.assert_not_called()+ @pytest.mark.parametrize(+ "queue_error,expected_type",+ [+ (+ psycopg.errors.ProtocolViolation(+ "server login has been failing, cached error: connect failed (server_login_retry)"+ ),+ PostHogInternalDatabaseError,+ ),+ (psycopg.errors.UndefinedTable("relation does not exist"), psycopg.errors.UndefinedTable),+ ],+ )+ def test_transient_queue_db_errors_are_raised_as_internal_database_errors(+ self, queue_error: psycopg.Error, expected_type: type[Exception]+ ) -> None:+ producer = _make_producer(is_resume=False)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ side_effect=queue_error,+ ):+ with pytest.raises(expected_type) as exc_info:+ producer.send_batch_notification(_make_batch_result(batch_index=0))++ assert type(exc_info.value) is expected_type+class TestPostgresProducerProperties:def test_sync_type_property(self) -> None: