Skip to content

: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.

fix(warehouse-sources): don't disable syncs for our own database outages (#89384)

Daniel RC6666f31791ca
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index 733d40177b0c..f9a9ce5b47de 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -157,7 +157,14 @@ def close_db_connections(fn: Callable[P, T]) -> Callable[P, T]:
return sync_wrapper
-def _is_stale_connection_read_only_error(error: Exception) -> bool:
+# The wording Postgres uses for SQLSTATE 25006, and the class name Django reports it under. Temporal
+# renders a wrapped activity failure as ``<ExceptionClass>: <message>``, so the prefix is how this
+# error identifies itself to code that only sees the flattened string across a workflow boundary.
+READ_ONLY_TRANSACTION_PHRASE = "read-only transaction"
+APP_DB_ERROR_PREFIX = f"{django.db.InternalError.__name__}:".lower()
+
+
+def is_stale_connection_read_only_error(error: Exception) -> bool:
"""Whether `error` is a write rejected because the connection outlived a primary failover.
A connection held open across a Postgres failover/switchover keeps talking to what is now a
@@ -167,7 +174,7 @@ def _is_stale_connection_read_only_error(error: Exception) -> bool:
``OperationalError``/``InterfaceError`` already cover, just a different DB-API exception class —
closing the connection and retrying reconnects to the current primary.
"""
- return isinstance(error, django.db.InternalError) and "read-only transaction" in str(error).lower()
+ return isinstance(error, django.db.InternalError) and READ_ONLY_TRANSACTION_PHRASE in str(error).lower()
async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, Any, T]]) -> T:
@@ -177,7 +184,7 @@ async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, An
recycle, failover, or deploy can leave a stale pooled connection that raises
``OperationalError`` / ``InterfaceError`` the first time it's used — or, for a write,
``InternalError`` if the stale connection now points at a demoted standby (see
- ``_is_stale_connection_read_only_error``). Evict the dead connection and retry once, so a
+ ``is_stale_connection_read_only_error``). Evict the dead connection and retry once, so a
transient blip at an activity's early connect-time reads succeeds on a fresh connection
instead of escaping as error-tracking noise. A second failure propagates — that's a
genuinely degraded DB, left to the caller's retry posture.
@@ -190,7 +197,7 @@ async def aretry_on_db_connection_drop(operation: Callable[[], Coroutine[Any, An
try:
return await operation()
except django.db.InternalError as e:
- if not _is_stale_connection_read_only_error(e):
+ if not is_stale_connection_read_only_error(e):
raise
await sync_to_async(_close_db_connections)()
return await operation()
@@ -207,7 +214,7 @@ def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
a long-lived worker pools connections through pgbouncer, so a pool recycle / failover
/ deploy can leave a stale pooled connection that raises ``OperationalError`` /
``InterfaceError`` on first use — or, for a write, ``InternalError`` if the stale
- connection now points at a demoted standby (see ``_is_stale_connection_read_only_error``).
+ connection now points at a demoted standby (see ``is_stale_connection_read_only_error``).
Evict the dead connection and retry once; a second failure propagates, left to the
caller's retry posture.
@@ -223,7 +230,7 @@ def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
try:
return operation()
except django.db.InternalError as e:
- if not _is_stale_connection_read_only_error(e):
+ if not is_stale_connection_read_only_error(e):
raise
_close_db_connections()
return operation()
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.py
index 2bd296134267..8f820e49dfb3 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
@@ -23,6 +23,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.client import sync_connect
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.schedule import trigger_schedule_buffer_one
+from posthog.temporal.common.utils import APP_DB_ERROR_PREFIX, READ_ONLY_TRANSACTION_PHRASE
from posthog.temporal.utils import CDPProducerWorkflowInputs, ExternalDataWorkflowInputs
from posthog.utils import get_machine_id
@@ -93,6 +94,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
EnrichTableSemanticsWorkflow,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ POSTHOG_DATABASE_UNAVAILABLE_MESSAGE,
ImportDataActivityInputs,
import_data_activity_sync,
)
@@ -205,6 +207,24 @@ def _customer_facing_error(cause: BaseException | None) -> str:
return message or str(cause)
+def _is_app_db_failure(internal_error: str) -> bool:
+ """Whether a run failed against PostHog's own app DB rather than the customer's source.
+
+ Temporal renders a wrapped activity failure as ``<ExceptionClass>: <message>`` (see
+ ``ApplicationError.__str__``), so the class the activity failed with survives into
+ ``internal_error``. ``django.db.InternalError`` is our own ORM: a source reaches a customer
+ database over a raw driver connection, whose read-only error is psycopg's
+ ``ReadOnlySqlTransaction`` and renders under that name instead. The two carry the same message,
+ which is why the class name has to do the telling.
+
+ The phrase narrows the class, mirroring ``is_stale_connection_read_only_error``: Django reports
+ corrupted data and failed-transaction states under the same class, and those are defects rather
+ than an outage that clears on its own.
+ """
+ normalized = internal_error.lower()
+ return normalized.startswith(APP_DB_ERROR_PREFIX) and READ_ONLY_TRANSACTION_PHRASE in normalized
+
+
def _fail_stale_running_schema(
schema_id: str, team_id: int, latest_error: str | None, logger: FilteringBoundLogger
) -> None:
@@ -222,7 +242,9 @@ def _fail_stale_running_schema(
logger.info("Reset stale Running schema status to Failed", schema_id=schema_id)
+# The workflow fills this in as a run unwinds — status, then the error fields on the failure
+# paths — so it is mutated after construction by design.
[email protected](frozen=False)
class UpdateExternalDataJobStatusInputs:
team_id: int
job_id: str | None
@@ -322,7 +344,17 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
else:
non_retryable_errors = {**Any_Source_Errors, **non_retryable_errors}
- has_non_retryable_error = error_message_matches(internal_error_normalized, non_retryable_errors.keys())
+ # A failure against our own app DB carries the same text as several source-side conditions
+ # (SQLSTATE 25006 after a failover, our pooler's "server login has been failing"), so
+ # matching it here would disable a sync whose source never failed, and hand the customer a
+ # message telling them to go fix a database that is working.
+ platform_failure = _is_app_db_failure(internal_error_normalized)
+ if platform_failure:
+ inputs.latest_error = POSTHOG_DATABASE_UNAVAILABLE_MESSAGE
+
+ has_non_retryable_error = not platform_failure and error_message_matches(
+ internal_error_normalized, non_retryable_errors.keys()
+ )
if has_non_retryable_error:
posthoganalytics.capture(
distinct_id=get_machine_id(),
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.py
index 784672aa1e45..ec206384d45d 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
@@ -21,9 +21,11 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job
UNEXPECTED_ERROR_MESSAGE,
UpdateExternalDataJobStatusInputs,
_customer_facing_error,
+ _is_app_db_failure,
trigger_schedule_buffer_one_activity,
update_external_data_job_model,
)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
class TestCustomerFacingError(SimpleTestCase):
@@ -53,6 +55,27 @@ class TestCustomerFacingError(SimpleTestCase):
assert _customer_facing_error(None) == UNEXPECTED_ERROR_MESSAGE
+class TestIsAppDbFailure(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # A pooled connection left on a demoted standby by a failover. Ours, and it clears.
+ ("failover", "InternalError", "cannot execute UPDATE in a read-only transaction", True),
+ # Django reports a corrupted index under the same class name. That one is a defect, so
+ # it must not be labeled a passing outage and told to wait for the next run.
+ ("corrupted_index", "InternalError", 'index "posthog_team_pkey" contains a zero page', False),
+ # psycopg raises the source-side read-only condition under its own class name, which is
+ # how a customer's write-on-read view stays the customer's to fix.
+ ("source_side", "ReadOnlySqlTransaction", "cannot execute INSERT in a read-only transaction", False),
+ ]
+ )
+ def test_only_the_failover_case_counts_as_ours(
+ self, _name: str, exc_type: str, message: str, expected: bool
+ ) -> None:
+ # str(ApplicationError) is what the workflow stores as internal_error, so build the input
+ # the same way rather than hand-writing the prefix this depends on.
+ assert _is_app_db_failure(str(ApplicationError(message, type=exc_type))) is expected
+
+
class TestTriggerScheduleBufferOneActivity(BaseTest):
@parameterized.expand([("billable", True), ("non_billable", False)])
def test_worker_shutdown_retry_keeps_the_runs_billable_flag(self, _name: str, billable: bool):
@@ -176,3 +199,62 @@ def test_failed_finalization_with_no_job_resets_stale_running_schema() -> None:
schema.refresh_from_db()
assert schema.status == ExternalDataSchema.Status.FAILED
assert schema.latest_error == "could not create the sync job"
+
+
+# transaction=True for the same reason as the test above: the activity resolves the source through
+# database_sync_to_async_pool, and the pool thread's connection can't see a test transaction.
+ [
+ # A customer relation whose own definition writes while we read it (a view or trigger that
+ # refreshes a materialized view). psycopg raises it on the source connection, so it reaches
+ # finalization under its own class name, and both the friendly message and the disable are
+ # correct.
+ ("raised_by_the_source", "ReadOnlySqlTransaction", True),
+ # The identical SQLSTATE 25006 wording from our own app DB after a primary failover, which
+ # Django reports as InternalError. Nothing is wrong with the source, and disabling makes the
+ # customer re-enable a sync our outage stopped.
+ ("raised_by_our_app_db", "InternalError", False),
+ ]
+)
[email protected]_db(transaction=True)
+def test_read_only_transaction_disables_the_schema_only_when_the_source_raised_it(
+ _name: str, exc_type: str, expect_disabled: bool
+) -> None:
+ org = Organization.objects.create(name="org")
+ team = Team.objects.create(organization=org, name="team")
+ source = ExternalDataSource.objects.create(team=team, source_type=ExternalDataSourceType.POSTGRES.value)
+ schema = ExternalDataSchema.objects.create(team=team, source=source, name="table")
+ job = ExternalDataJob.objects.create(
+ team=team, pipeline=source, schema=schema, status=ExternalDataJob.Status.RUNNING, rows_synced=0
+ )
+
+ env = ActivityEnvironment()
+ inputs = UpdateExternalDataJobStatusInputs(
+ team_id=team.id,
+ job_id=str(job.id),
+ schema_id=str(schema.id),
+ source_id=str(source.id),
+ status=ExternalDataJob.Status.FAILED,
+ internal_error=str(ApplicationError("cannot execute UPDATE in a read-only transaction", type=exc_type)),
+ latest_error="cannot execute UPDATE in a read-only transaction",
+ )
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_rows", return_value=0
+ ),
+ mock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.finish_row_tracking"),
+ mock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.capture_exception"),
+ mock.patch("posthoganalytics.capture"),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.update_should_sync"
+ ) as mock_update_should_sync,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.update_external_job_status"
+ ) as mock_update_job_status,
+ ):
+ asyncio.run(env.run(update_external_data_job_model, inputs))
+
+ assert mock_update_should_sync.called is expect_disabled
+ customer_message = mock_update_job_status.call_args.kwargs["latest_error"] or ""
+ assert ("tries to write to your database" in customer_message) is expect_disabled
diff --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.py
index 360ca20bcbea..3a4b712085af 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
@@ -5,7 +5,7 @@ import datetime as dt
import dataclasses
from typing import Any, NoReturn, Optional
-from django.db import InterfaceError, OperationalError
+from django.db import InterfaceError, InternalError, OperationalError
from django.db.models import Prefetch
from jsonpath_ng.exceptions import JSONPathError
@@ -24,6 +24,7 @@ from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.shutdown import ShutdownMonitor
+from posthog.temporal.common.utils import is_stale_connection_read_only_error
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
@@ -235,18 +236,25 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
):
try:
return await _import_data_with_reporting(inputs, logger)
- except (OperationalError, InterfaceError, PostHogInternalDatabaseError) as e:
+ except (OperationalError, InterfaceError, InternalError, PostHogInternalDatabaseError) as e:
# The setup phase (resolving the job/schema/source rows for this run) reads PostHog's
# own app DB through the Django ORM before the source's error handling takes over. A
- # transient connection-pool blip there — a PgBouncer server_login_retry cooldown, the
- # primary briefly in recovery — raises this exception type, which can only mean our own
- # infra, never the customer's source (every source talks to a customer database over a
- # raw driver connection, not the ORM). Re-raise as NonReportableError so Temporal
- # retries the whole activity and it self-heals, rather than failing the sync with the
- # raw driver string as latest_error. _handle_import_error already classifies these types
- # this way once the run is under way; this covers the setup calls that run before it.
+ # transient blip there — a PgBouncer server_login_retry cooldown, or a pooled connection
+ # left on a demoted standby by a failover, which rejects our writes as InternalError —
+ # raises these exception types, which can only mean our own infra, never the customer's
+ # source (every source talks to a customer database over a raw driver connection, not
+ # the ORM). Re-raise as NonReportableError so Temporal retries the whole activity and it
+ # self-heals. The raw driver string stays in the log but must not become the message
+ # that escapes: see POSTHOG_DATABASE_UNAVAILABLE_MESSAGE. _handle_import_error already
+ # classifies these types this way once the run is under way; this covers the setup calls
+ # that run before it.
+ if isinstance(e, InternalError) and not is_stale_connection_read_only_error(e):
+ # InternalError also covers corrupted data/indexes and failed-transaction states.
+ # Those are deterministic defects, so retrying burns the budget, and NonReportableError
+ # would keep them out of error tracking behind a message saying nothing is wrong.
+ raise
await logger.awarning(str(e))
- raise NonReportableError(str(e)) from e
+ raise NonReportableError(POSTHOG_DATABASE_UNAVAILABLE_MESSAGE) from e
async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger: FilteringBoundLogger) -> PipelineResult:
@@ -531,6 +539,18 @@ INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE = (
)
+# What a customer reads when a lookup against PostHog's own app DB fails. It deliberately repeats
+# none of the driver wording: the workflow hands whatever message escapes an activity to the
+# finalization activity, which substring-matches it against every source's non-retryable patterns,
+# and the Postgres map carries the same "in a read-only transaction" and "server login has been
+# failing" strings our own pooler and failovers produce. A raw message there disables a working
+# sync and tells the customer to go fix their database. The raw text stays in the logs.
+POSTHOG_DATABASE_UNAVAILABLE_MESSAGE = (
+ "This sync stopped because of a temporary problem on PostHog's side. Your source is fine, "
+ "and the sync will run again automatically."
+)
+
+
async def _handle_import_error(
job_inputs: PipelineInputs,
logger: FilteringBoundLogger,
@@ -665,19 +685,27 @@ async def _handle_import_error(
await logger.adebug("Transient object-store error - re-raising for Temporal retry")
raise NonReportableError(error_msg) from error
- # A Django OperationalError/InterfaceError here comes from a lookup against PostHog's own app
- # DB (e.g. resolving a team or CustomPropertySource for the person-property staging hook) —
- # every source that talks to a customer's own database (Postgres, MySQL, Redshift) does so over
- # a raw driver connection, never Django's ORM, so this exception type can only mean a transient
- # connection-pool blip on our side (e.g. a PgBouncer query_wait_timeout under load), not a
- # customer data or config problem. Same classification already used for app-DB blips in
- # delta_table_ref.is_transient_maintenance_error. PostHogInternalDatabaseError is the same
- # condition already reclassified by shared pipeline code (e.g. cdp_producer's should_run check)
- # specifically so it wouldn't be mistaken for a customer-side failure here — honor that by type.
- if isinstance(error, OperationalError | InterfaceError | PostHogInternalDatabaseError):
+ # A Django OperationalError/InterfaceError/InternalError here comes from a lookup against
+ # PostHog's own app DB (e.g. resolving a team or CustomPropertySource for the person-property
+ # staging hook) — every source that talks to a customer's own database (Postgres, MySQL,
+ # Redshift) does so over a raw driver connection, never Django's ORM, so these exception types
+ # can only mean a transient blip on our side, not a customer data or config problem. The blip is
+ # a connection-pool one for OperationalError/InterfaceError (e.g. a PgBouncer query_wait_timeout
+ # under load) and a failover for InternalError: a pooled connection that outlived a primary
+ # switchover now points at a demoted standby, so our writes come back as psycopg's
+ # ReadOnlySqlTransaction. InternalError alone is too broad for that — it also covers corrupted
+ # data/indexes and failed-transaction states, which are deterministic defects that must stay
+ # reportable — so it is matched through the shared read-only predicate. Same classification already used
+ # for app-DB blips in delta_table_ref.is_transient_maintenance_error. PostHogInternalDatabaseError
+ # is the same condition already reclassified by shared pipeline code (e.g. cdp_producer's
+ # should_run check) specifically so it wouldn't be mistaken for a customer-side failure here —
+ # honor that by type.
+ if isinstance(
+ error, OperationalError | InterfaceError | PostHogInternalDatabaseError
+ ) or is_stale_connection_read_only_error(error):
await logger.awarning(error_msg)
await logger.adebug("Transient app-DB error - re-raising for Temporal retry")
- raise NonReportableError(error_msg) from error
+ raise NonReportableError(POSTHOG_DATABASE_UNAVAILABLE_MESSAGE) from error
# Cross-source non-retryable errors (missing primary key on an incremental table, bad SSH tunnel
# auth, a widened column type) are raised from shared pipeline code, not any one source. The
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.py
index 6f2907882407..0e61b4f6879d 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
@@ -7,7 +7,7 @@ import pytest
from posthog.test.base import BaseTest
from unittest import mock
-from django.db import InterfaceError, OperationalError
+from django.db import InterfaceError, InternalError, OperationalError
from jsonpath_ng.exceptions import JsonPathParserError
from parameterized import parameterized
@@ -206,15 +206,24 @@ async def test_schema_deleted_mid_sync_routes_through_handler():
source.parse_config.assert_not_called()
+ [
+ ("pooler_cooldown", OperationalError, "server login has been failing, cached error: (server_login_retry)"),
+ ("failover_read_only", InternalError, "cannot execute INSERT in a read-only transaction"),
+ ]
+)
@pytest.mark.asyncio
-async def test_transient_app_db_error_in_setup_is_retryable_not_raw():
+async def test_transient_app_db_error_in_setup_is_retryable_not_raw(
+ _name: str, error_cls: type[Exception], message: str
+):
# The setup phase resolves this run's job/schema/source rows over the Django ORM (our own app
- # DB). A transient connection-pool blip there — e.g. a PgBouncer server_login_retry cooldown —
- # raises a Django OperationalError before the source's error handling runs. It's our infra, not
- # the customer's source, so it must be re-raised as NonReportableError (Temporal retries the
- # whole activity and it self-heals) rather than escaping raw and being stored verbatim as
- # latest_error while minting error-tracking noise.
- error = OperationalError("server login has been failing, cached error: (server_login_retry)")
+ # DB). A transient blip there — a PgBouncer server_login_retry cooldown, or a pooled connection
+ # left on a demoted standby after a failover — raises before the source's error handling runs.
+ # It's our infra, not the customer's source, so it must be re-raised as NonReportableError
+ # (Temporal retries the whole activity and it self-heals) rather than escaping raw and being
+ # stored verbatim as latest_error while minting error-tracking noise. Both driver strings are
+ # wording the Postgres source's non-retryable map matches, so the message must not survive.
+ error = error_cls(message)
source = mock.MagicMock(spec=SimpleSource)
with (
@@ -225,10 +234,30 @@ async def test_transient_app_db_error_in_setup_is_retryable_not_raw():
await import_data_activity_sync(_inputs())
assert exc_info.value.__cause__ is error
+ assert str(exc_info.value) == module.POSTHOG_DATABASE_UNAVAILABLE_MESSAGE
handle_mock.assert_not_awaited()
source.source_for_pipeline.assert_not_called()
+async def test_non_failover_internal_error_in_setup_is_not_hidden_as_a_platform_outage():
+ # InternalError is the Django class for the failover case above, but also for corrupted data or
+ # indexes and failed-transaction states. Those are deterministic defects: wrapping them as
+ # NonReportableError would spend the retry budget on an error no retry fixes, and keep it out of
+ # error tracking behind a message telling the customer nothing is wrong.
+ error = InternalError('index "posthog_team_pkey" contains unexpected zero page at block 0')
+ source = mock.MagicMock(spec=SimpleSource)
+
+ with (
+ _patched_activity(source),
+ mock.patch.object(module, "_get_external_data_job", new=mock.AsyncMock(side_effect=error)),
+ ):
+ with pytest.raises(InternalError) as exc_info:
+ await import_data_activity_sync(_inputs())
+
+ assert exc_info.value is error
+
+
@pytest.mark.asyncio
async def test_source_classified_retryable_error_logged_as_warning_not_exception():
# A rate-limit / transient error the source retries internally reaches _handle_import_error only
@@ -383,6 +412,12 @@ async def test_rest_client_retryable_error_logged_as_warning_without_source_opt_
# misconfigured source host would produce, so it must get the same NonReportableError
# treatment as the Django exception types above, not fall through to the default branch.
("posthog_internal_database_error", PostHogInternalDatabaseError, "Failed to check hog function triggers"),
+ # A pooled connection that outlived a primary failover now talks to a demoted standby, so
+ # our own writes fail with SQLSTATE 25006. Django surfaces psycopg's ReadOnlySqlTransaction
+ # as InternalError, a different DB-API class from the two above, so it needs its own arm
+ # here. Without one it falls through to the source's non-retryable map, whose Postgres entry
+ # matches the identical wording a customer's write-on-read view produces.
+ ("read_only_transaction", InternalError, "cannot execute UPDATE in a read-only transaction"),
]
)
@pytest.mark.asyncio
@@ -408,10 +443,36 @@ async def test_app_db_connection_error_reraised_as_non_reportable(_name: str, er
await module._handle_import_error(mock.MagicMock(), logger, error)
assert exc_info.value.__cause__ is error
+ # The raw driver string is wording the source non-retryable maps match on, and the workflow
+ # hands whatever escapes here to the finalization activity as the customer's latest_error.
+ # Carry the platform message instead so neither can mistake our outage for their source.
+ assert str(exc_info.value) == module.POSTHOG_DATABASE_UNAVAILABLE_MESSAGE
logger.awarning.assert_awaited_once()
logger.aexception.assert_not_awaited()
+async def test_non_failover_internal_error_falls_through_to_the_default_branch():
+ # Same narrowing as the setup phase, at the mid-run handler: only the failover read-only case is
+ # ours to retry silently. A corrupted index has to keep escaping so error tracking sees it.
+ error = InternalError('index "posthog_team_pkey" contains unexpected zero page at block 0')
+ source = mock.MagicMock(spec=SimpleSource)
+ source.get_non_retryable_errors.return_value = {}
+ source.get_retryable_errors.return_value = set()
+
+ logger = mock.MagicMock()
+ logger.awarning = mock.AsyncMock()
+ logger.aexception = mock.AsyncMock()
+ logger.adebug = mock.AsyncMock()
+
+ with mock.patch.object(module.SourceRegistry, "get_source", return_value=source):
+ with pytest.raises(InternalError) as exc_info:
+ await module._handle_import_error(mock.MagicMock(), logger, error)
+
+ assert exc_info.value is error
+ logger.aexception.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_transient_object_store_error_reraised_as_non_reportable():
# A transient S3 credential-provider blip (IMDS/STS) talking to our own data-warehouse bucket,
@@ -874,7 +935,13 @@ async def test_integration_failure_is_classified_before_the_bare_404_rule():
# So the message is not free text: no pattern may be a substring of it. This sweeps every
# registered source rather than the shared dict alone, because a source-specific pattern
# (a bare word like "unavailable") would do it just as well.
-def test_the_customer_facing_message_matches_no_non_retryable_pattern():
+ [
+ ("integration_credential", "INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE"),
+ ("posthog_database", "POSTHOG_DATABASE_UNAVAILABLE_MESSAGE"),
+ ]
+)
+def test_the_customer_facing_message_matches_no_non_retryable_pattern(_name: str, message_attr: str):
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
@@ -887,8 +954,9 @@ def test_the_customer_facing_message_matches_no_non_retryable_pattern():
# test pass while checking nothing.
assert len(patterns) > 20, f"expected the source registry to contribute patterns, got {len(patterns)}"
- offenders = [p for p in patterns if error_message_matches(module.INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE, [p])]
+ message = getattr(module, message_attr)
+ offenders = [p for p in patterns if error_message_matches(message, [p])]
assert offenders == [], (
- f"These non-retryable patterns match the integration-credential message, so an exhausted "
+ f"These non-retryable patterns match {message_attr}, so an exhausted "
f"retry budget would disable the customer's schema: {offenders}"
)