: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): explain a postgres sync that ran out of retries (#85517)
posthog[bot]a8a2e3dff487
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 1c837a98bafc..0347d272aae5 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@@ -482,7 +482,19 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpudisable_exclude_workflow_id=activity.info().workflow_id,)elif not platform_failure:- transient_message = _transient_error_message(internal_error_normalized)+ # A retryable failure that outlasted the whole retry budget lands here with+ # `latest_error` still set to the raw driver text. The generic transient copy is+ # consulted first; the source's own exhaustion messages cover the classes it does not+ # name. Retryability is untouched: the schema is not disabled and the next scheduled+ # run still tries.+ transient_message = _transient_error_message(internal_error_normalized) or next(+ (+ message+ for error, message in source_cls.get_retry_exhausted_errors().items()+ if error_message_matches(internal_error_normalized, [error])+ ),+ None,+ )if transient_message is not None:inputs.latest_error = transient_messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex b504104d0590..be06c1dd352e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -242,6 +242,27 @@ class _BaseSource(ABC, Generic[ConfigType]):return set()+ def get_retry_exhausted_errors(self) -> dict[str, str]:+ """Customer-facing messages for retryable failures that survived the whole retry budget.++ Entries here do NOT change retryability — a matching failure keeps retrying and the schema+ stays enabled. They only replace the raw driver text the job would otherwise store once+ Temporal's retries run out, so `latest_error` names the failure class and a next action+ instead of leaking connection internals.++ Keys are partial error messages matched against `str(error)`, and should be drawn from+ `get_retryable_errors` — a class the source never retries has no exhaustion to describe.+ `get_non_retryable_errors` is consulted first, so a message matching both keeps the+ non-retryable wording. The finalizer's generic `Transient_Error_Messages` map is consulted+ next, so entries here only apply to classes that map does not name.++ Returns `dict[str, str]`:+ key = a partial error message to match on+ value = the message to store on the failed job+ """++ return {}+def get_required_parent_schemas(self, schema_name: str) -> list[str]:"""Sibling schemas `schema_name` reads from the warehouse instead of re-fetching.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex ce35b101457c..65b16dda9320 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -258,6 +258,38 @@ _SSL_UNSUPPORTED_ERROR = ("your database server, or connect through an SSH tunnel instead.")+# Terminal messages for the transient classes in `get_retryable_errors`. Those stay retryable, but+# once every retry is spent the job stores whatever the driver said — a raw libpq or pooler string+# carrying the customer's host and IP and no next action. Each message below names the class and+# what to check, and deliberately carries no connection detail. See `get_retry_exhausted_errors`.+_CONNECTION_DROPPED_EXHAUSTED_MESSAGE = (+ "PostHog's connection to your database kept closing before the sync could finish, and "+ "reconnecting didn't help. The database, a connection pooler, a firewall, or an SSH tunnel is "+ "ending the connection early. Check those for idle or connection lifetime timeouts, restarts, "+ "and failovers. This sync is still enabled and will run again on its next schedule."+)++_SERVER_UNAVAILABLE_EXHAUSTED_MESSAGE = (+ "Your database wasn't accepting connections, and it was still unavailable after every retry. It "+ "reported that it's starting up, recovering, or shutting down. Check that the database is "+ "running and healthy. This sync is still enabled and will run again on its next schedule."+)++_CONNECTION_LIMIT_EXHAUSTED_MESSAGE = (+ "Your database had no free connection slots for PostHog, and none freed up before the retries "+ "ran out. Raise the connection limit on the database or its pooler, or reduce how many other "+ "clients connect at the same time. This sync is still enabled and will run again on its next "+ "schedule."+)++_RECOVERY_CONFLICT_EXHAUSTED_MESSAGE = (+ "Your read replica kept canceling PostHog's reads because it had to apply changes from the "+ "primary that removed rows the sync was still reading, and the conflict outlasted every retry. "+ "Increase max_standby_streaming_delay on the replica, enable hot_standby_feedback, or point the "+ "connection at the primary database. This sync is still enabled and will run again on its next "+ "schedule."+)+@SourceRegistry.registerclass PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):@@ -1006,6 +1038,24 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa"conflict with recovery",}+ def get_retry_exhausted_errors(self) -> dict[str, str]:+ # Every substring `get_retryable_errors` keeps retryable, mapped to the message the job+ # stores once Temporal's retries are spent. Without this the terminal `latest_error` is the+ # raw driver text (for example libpq's "connection to server at "<host>" (<ip>), port <port>+ # failed: server closed the connection unexpectedly"), which leaks the customer's connection+ # detail, offers no next action, and reads the same whether a sync dropped once or has been+ # failing all week.+ #+ # Built from the same tuples as `get_retryable_errors` so a substring added there can't+ # silently fall back to raw driver text here.+ return {+ **dict.fromkeys(_CONNECTION_DROPPED_ERROR_SUBSTRINGS, _CONNECTION_DROPPED_EXHAUSTED_MESSAGE),+ **dict.fromkeys(_POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS, _CONNECTION_DROPPED_EXHAUSTED_MESSAGE),+ **dict.fromkeys(_SERVER_STARTING_UP_ERROR_SUBSTRINGS, _SERVER_UNAVAILABLE_EXHAUSTED_MESSAGE),+ **dict.fromkeys(_CONNECTION_LIMIT_ERROR_SUBSTRINGS, _CONNECTION_LIMIT_EXHAUSTED_MESSAGE),+ "conflict with recovery": _RECOVERY_CONFLICT_EXHAUSTED_MESSAGE,+ }+def reconcile_schema_metadata(self,source: "ExternalDataSource",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 97c7da79bbb2..8985d3785fdb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -601,6 +601,44 @@ class TestPostgresSourceNonRetryableErrors:assert error_message_matches(error_msg, source.get_retryable_errors())assert not error_message_matches(error_msg, source.get_non_retryable_errors().keys())+ @pytest.mark.parametrize(+ "error_msg,expected_phrase",+ [+ (+ 'OperationalError: connection failed: connection to server at "db.example.com" (10.0.0.1), port 5432 failed: server closed the connection unexpectedly',+ "closing",+ ),+ (+ 'OperationalError: connection failed: connection to server at "db.example.com" (10.0.0.1), port 5432 failed: FATAL: the database system is starting up',+ "accepting connections",+ ),+ (+ 'OperationalError: connection failed: connection to server at "db.example.com" (10.0.0.1), port 5432 failed: FATAL: sorry, too many clients already',+ "connection slots",+ ),+ ],+ )+ def test_exhausted_retries_replace_raw_driver_text(self, source, error_msg, expected_phrase):+ # Once Temporal's retries run out these land on the job as-is, so without a mapping the+ # customer reads libpq's host and IP and gets no next action. Mirror the finalizer's+ # first-match selection over get_retry_exhausted_errors.+ message = next(+ (+ friendly+ for pattern, friendly in source.get_retry_exhausted_errors().items()+ if error_message_matches(error_msg, [pattern])+ ),+ None,+ )+ assert message is not None, f"Exhausted retryable error must surface a message: {error_msg}"+ assert expected_phrase in message.lower()+ assert "db.example.com" not in message and "10.0.0.1" not in message++ def test_every_retryable_error_has_an_exhaustion_message(self, source):+ # A transient substring added to postgres.py flows into get_retryable_errors automatically,+ # so one missing here would silently fall back to storing the raw driver text.+ assert source.get_retryable_errors() == set(source.get_retry_exhausted_errors().keys())+@pytest.mark.parametrize("error_msg",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.pyindex 7031d7da3fc6..017d99ba95c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py@@ -30,6 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_jobtrigger_schedule_buffer_one_activity,update_external_data_job_model,)+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import (+ _CONNECTION_LIMIT_EXHAUSTED_MESSAGE,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -281,6 +284,15 @@ def test_read_only_transaction_disables_the_schema_only_when_the_source_raised_i"SSL SYSCALL error: EOF detected",TRANSIENT_SOURCE_CONNECTION_MESSAGE,),+ # A connect-time capacity refusal. The generic map has no entry for it, so the Postgres+ # source's own exhaustion message fills the gap.+ (+ "postgres_connection_limit",+ ExternalDataSourceType.POSTGRES,+ 'connection failed: connection to server at "198.51.100.7", port 5432 failed: '+ "FATAL: sorry, too many clients already",+ _CONNECTION_LIMIT_EXHAUSTED_MESSAGE,+ ),# pymysql renders a mid-query drop as a bare code/message tuple.("mysql_lost_connection",