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(data-imports): retry job creation through a read-only-transaction failover (#88301)

Tom Owers61f22f3fe57e
diff --git a/posthog/temporal/common/db_errors.py b/posthog/temporal/common/db_errors.py
index e5eaffcee139..688d53cf2221 100644
--- a/posthog/temporal/common/db_errors.py
+++ b/posthog/temporal/common/db_errors.py
@@ -1,4 +1,4 @@
-from django.db import InterfaceError, OperationalError
+from django.db import InterfaceError, InternalError, OperationalError
# Substrings identifying transient Postgres failures. pgbouncer kills queries that wait too long
# for a backend connection with `query_wait_timeout`, and surfaces dropped/reset backend
@@ -42,12 +42,21 @@ _TRANSIENT_DB_ERROR_MARKERS = (
# through to the message markers above.
_TRANSIENT_SQLSTATE_PREFIXES = ("57P",)
+# read_only_sql_transaction: a primary/replica failover briefly leaves the connection's target
+# read-only until promotion finishes or the pooler redirects to the new primary. Matched exactly
+# rather than by class prefix, because SQLSTATE class 25 (invalid transaction state) also covers
+# codes that are real transaction-handling bugs, not infra hiccups. psycopg raises this under
+# InternalError, not OperationalError, hence the wider isinstance check below.
+_TRANSIENT_SQLSTATES = ("25006",)
+
def is_transient_db_error(error: BaseException) -> bool:
- if not isinstance(error, OperationalError | InterfaceError):
+ if not isinstance(error, OperationalError | InterfaceError | InternalError):
return False
sqlstate = getattr(error.__cause__, "sqlstate", None)
- if isinstance(sqlstate, str) and sqlstate.startswith(_TRANSIENT_SQLSTATE_PREFIXES):
+ if isinstance(sqlstate, str) and (
+ sqlstate.startswith(_TRANSIENT_SQLSTATE_PREFIXES) or sqlstate in _TRANSIENT_SQLSTATES
+ ):
return True
message = str(error)
return any(marker in message for marker in _TRANSIENT_DB_ERROR_MARKERS)
diff --git a/posthog/temporal/common/test_db_errors.py b/posthog/temporal/common/test_db_errors.py
index 49e9c9e0896e..d096febebfb1 100644
--- a/posthog/temporal/common/test_db_errors.py
+++ b/posthog/temporal/common/test_db_errors.py
@@ -1,6 +1,6 @@
import pytest
-from django.db import InterfaceError, OperationalError
+from django.db import InterfaceError, InternalError, OperationalError
from posthog.temporal.common.db_errors import is_transient_db_error
@@ -54,3 +54,19 @@ def test_is_transient_db_error_by_sqlstate(sqlstate: str, expected: bool) -> Non
error = OperationalError("some driver-specific message")
error.__cause__ = _WithSqlstate(sqlstate)
assert is_transient_db_error(error) is expected
+
+
+def test_is_transient_db_error_for_read_only_transaction_failover() -> None:
+ # psycopg raises this under InternalError, not OperationalError — a primary/replica failover
+ # briefly rejects writes with this exact SQLSTATE until promotion completes.
+ error = InternalError("cannot execute INSERT in a read-only transaction")
+ error.__cause__ = _WithSqlstate("25006")
+ assert is_transient_db_error(error) is True
+
+
+def test_is_transient_db_error_rejects_other_internal_errors() -> None:
+ # Class 25 (invalid transaction state) has other codes that are real bugs, not infra hiccups —
+ # only the exact read-only-transaction code should be treated as transient.
+ error = InternalError("current transaction is aborted")
+ error.__cause__ = _WithSqlstate("25P02")
+ assert is_transient_db_error(error) is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/db_retry.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/db_retry.py
index aca45fd60f2d..b3c861ad19b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/db_retry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/db_retry.py
@@ -2,7 +2,9 @@ import time
from collections.abc import Callable
from typing import ParamSpec, TypeVar
-from django.db import OperationalError, close_old_connections
+from django.db import InternalError, OperationalError, close_old_connections
+
+from posthog.temporal.common.db_errors import is_transient_db_error
_P = ParamSpec("_P")
_R = TypeVar("_R")
@@ -16,16 +18,19 @@ def _backoff_sleep(attempt: int) -> None:
def retry_on_operational_error(fn: Callable[_P, _R]) -> Callable[_P, _R]:
- """Retry a synchronous, idempotent DB operation on a transient ``OperationalError``.
+ """Retry a synchronous, idempotent DB operation on a transient DB error.
Temporal activities run in a long-lived worker outside Django's request cycle, so a pooled
Postgres connection can be closed server-side while idle, or the connection pooler can reject
a query with a wait timeout (`query_wait_timeout`) when the pool is saturated. Both surface as
- a transient ``OperationalError`` that clears once a healthy connection is used.
+ a transient ``OperationalError`` that clears once a healthy connection is used. A primary/
+ replica failover surfaces differently — Postgres rejects the write with "read-only
+ transaction", which Django wraps as ``InternalError`` — so that case is only retried when
+ ``is_transient_db_error`` recognizes it, to avoid masking genuine ``InternalError`` bugs.
``close_old_connections()`` evicts a connection a failed query marked unusable so the next
- attempt runs on a fresh one; the backoff gives a saturated pool time to drain rather than
- retrying straight back into the same wait timeout. Only wrap idempotent operations — each
- attempt re-runs ``fn`` from scratch.
+ attempt runs on a fresh one; the backoff gives a saturated pool (or an in-progress failover)
+ time to clear rather than retrying straight back into the same failure. Only wrap idempotent
+ operations — each attempt re-runs ``fn`` from scratch.
"""
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
@@ -33,7 +38,9 @@ def retry_on_operational_error(fn: Callable[_P, _R]) -> Callable[_P, _R]:
while True:
try:
return fn(*args, **kwargs)
- except OperationalError:
+ except (OperationalError, InternalError) as e:
+ if isinstance(e, InternalError) and not is_transient_db_error(e):
+ raise
attempt += 1
if attempt >= _MAX_ATTEMPTS:
raise
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_db_retry.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_db_retry.py
index 6f56323bc65e..cdea62789e4d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_db_retry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_db_retry.py
@@ -2,7 +2,7 @@ import pytest
from unittest import mock
from unittest.mock import patch
-from django.db import OperationalError
+from django.db import InternalError, OperationalError
from django.test import SimpleTestCase
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (
@@ -12,6 +12,20 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.d
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"
+class _WithSqlstate(Exception):
+ def __init__(self, sqlstate: str) -> None:
+ super().__init__(sqlstate)
+ self.sqlstate = sqlstate
+
+
+def _read_only_transaction_error() -> InternalError:
+ # Mirrors how Django wraps psycopg's ReadOnlySqlTransaction: the original driver exception
+ # (carrying the SQLSTATE) becomes __cause__.
+ error = InternalError("cannot execute INSERT in a read-only transaction")
+ error.__cause__ = _WithSqlstate("25006")
+ return error
+
+
class TestRetryOnOperationalError(SimpleTestCase):
def test_retries_transient_operational_error_then_succeeds(self):
fn = mock.Mock(
@@ -69,3 +83,35 @@ class TestRetryOnOperationalError(SimpleTestCase):
fn.assert_called_once_with(1, 2, key="value")
assert result == "result"
+
+ def test_retries_read_only_transaction_error_then_succeeds(self):
+ # A primary/replica failover surfaces as InternalError (SQLSTATE 25006), not
+ # OperationalError, and clears once a fresh connection lands on the new primary.
+ fn = mock.Mock(side_effect=[_read_only_transaction_error(), "result"])
+
+ with (
+ patch(f"{_MODULE}.close_old_connections") as close,
+ patch(f"{_MODULE}.time.sleep") as sleep,
+ ):
+ result = retry_on_operational_error(fn)()
+
+ assert result == "result"
+ assert fn.call_count == 2
+ assert close.call_count == 1
+ assert sleep.call_args_list == [mock.call(2)]
+
+ def test_does_not_retry_unrelated_internal_error(self):
+ # Only the specific transient read-only-transaction case should be retried — a generic
+ # InternalError is a real bug and must surface immediately, not be masked for 12s.
+ fn = mock.Mock(side_effect=InternalError("current transaction is aborted"))
+
+ with (
+ patch(f"{_MODULE}.close_old_connections") as close,
+ patch(f"{_MODULE}.time.sleep") as sleep,
+ ):
+ with pytest.raises(InternalError):
+ retry_on_operational_error(fn)()
+
+ assert fn.call_count == 1
+ close.assert_not_called()
+ sleep.assert_not_called()