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 transient query_wait_timeout in pipeline bookkeeping writes (#75752)

Tom Owersddee3245d9e0
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 1b49950150bc..d60b30cb6d2b 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -445,7 +445,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("partition_size_override", None)
self.sync_type_config.pop("partition_mode_override", None)
self.sync_type_config.pop("partitioning_keys_override", None)
- self.save()
+ # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
+ # `_get_before_update` SELECT (see save()).
+ self.save(skip_activity_log=True)
# --- In-place repartition controller state ------------------------------------------------
# These keys drive the automated, no-source-pull repartition that bounds per-partition memory
@@ -557,7 +559,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
if earliest_value is not None:
staged["earliest_value"] = self._serialize_incremental_value(earliest_value)
self.sync_type_config["incremental_staged"] = staged
- self.save()
+ # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
+ # `_get_before_update` SELECT (see save()).
+ self.save(skip_activity_log=True)
def promote_staged_incremental_values(self, run_uuid: str) -> bool:
staged = self.sync_type_config.get("incremental_staged")
@@ -568,7 +572,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
if "earliest_value" in staged:
self.sync_type_config["incremental_field_earliest_value"] = staged["earliest_value"]
self.sync_type_config.pop("incremental_staged", None)
- self.save()
+ self.save(skip_activity_log=True)
return True
def _serialize_incremental_value(self, value: Any) -> Any:
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
new file mode 100644
index 000000000000..aca45fd60f2d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/db_retry.py
@@ -0,0 +1,43 @@
+import time
+from collections.abc import Callable
+from typing import ParamSpec, TypeVar
+
+from django.db import OperationalError, close_old_connections
+
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
+_MAX_ATTEMPTS = 4
+
+
+def _backoff_sleep(attempt: int) -> None:
+ """Linear growth capped at 30s (2s, 4s, 6s, ...), matching OAuthMixin.get_oauth_integration."""
+ time.sleep(min(2 * attempt, 30))
+
+
+def retry_on_operational_error(fn: Callable[_P, _R]) -> Callable[_P, _R]:
+ """Retry a synchronous, idempotent DB operation on a transient ``OperationalError``.
+
+ 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.
+ ``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.
+ """
+
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ attempt = 0
+ while True:
+ try:
+ return fn(*args, **kwargs)
+ except OperationalError:
+ attempt += 1
+ if attempt >= _MAX_ATTEMPTS:
+ raise
+ close_old_connections()
+ _backoff_sleep(attempt)
+
+ return wrapper
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 65299e549f61..75720465779e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -19,6 +19,9 @@ from products.warehouse_sources.backend.models.external_data_schema import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (
+ retry_on_operational_error,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.metrics import POST_LOAD_DURATION_SECONDS
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
@@ -42,7 +45,9 @@ LOGGER = get_logger(__name__)
async def update_job_row_count(job_id: str, count: int, logger: FilteringBoundLogger) -> None:
await logger.adebug(f"Updating rows_synced with +{count}")
await database_sync_to_async_pool(
- lambda: ExternalDataJob.objects.filter(id=job_id).update(rows_synced=F("rows_synced") + count)
+ retry_on_operational_error(
+ lambda: ExternalDataJob.objects.filter(id=job_id).update(rows_synced=F("rows_synced") + count)
+ )
)()
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
new file mode 100644
index 000000000000..6f56323bc65e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_db_retry.py
@@ -0,0 +1,71 @@
+import pytest
+from unittest import mock
+from unittest.mock import patch
+
+from django.db import OperationalError
+from django.test import SimpleTestCase
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (
+ retry_on_operational_error,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"
+
+
+class TestRetryOnOperationalError(SimpleTestCase):
+ def test_retries_transient_operational_error_then_succeeds(self):
+ fn = mock.Mock(
+ side_effect=[
+ OperationalError("query_wait_timeout"),
+ OperationalError("query_wait_timeout"),
+ "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 == 3
+ # The poisoned connection is evicted before each retry, but not on the successful attempt.
+ assert close.call_count == 2
+ # Backoff grows per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.
+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]
+
+ def test_success_does_not_evict_connection(self):
+ fn = mock.Mock(return_value="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"
+ close.assert_not_called()
+ sleep.assert_not_called()
+
+ def test_reraises_after_exhausting_attempts(self):
+ fn = mock.Mock(side_effect=OperationalError("query_wait_timeout"))
+
+ with (
+ patch(f"{_MODULE}.close_old_connections"),
+ patch(f"{_MODULE}.time.sleep") as sleep,
+ ):
+ with pytest.raises(OperationalError):
+ retry_on_operational_error(fn)()
+
+ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry the activity.
+ assert fn.call_count == 4
+ assert sleep.call_args_list == [mock.call(2), mock.call(4), mock.call(6)]
+
+ def test_passes_through_args_and_kwargs(self):
+ fn = mock.Mock(return_value="result")
+
+ result = retry_on_operational_error(fn)(1, 2, key="value")
+
+ fn.assert_called_once_with(1, 2, key="value")
+ assert result == "result"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index 9c0ccc5f6c12..13c9817cb36e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -3,6 +3,8 @@ import uuid
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.db import OperationalError
+
import pyarrow as pa
from parameterized import parameterized
@@ -12,9 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.l
IncrementalFieldMissingFromDataError,
get_incremental_field_value,
run_post_load_operations,
+ update_job_row_count,
)
_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load"
+_DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"
_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"
_REPARTITION_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
@@ -280,3 +284,25 @@ class TestGetIncrementalFieldValue:
schema = self._schema("updated_at", sync_type=sync_type)
assert get_incremental_field_value(schema, table) is None
+
+
+class TestUpdateJobRowCount:
+ @pytest.mark.asyncio
+ async def test_retries_transient_query_wait_timeout_then_succeeds(self):
+ # A saturated pgbouncer pool rejects the row-count UPDATE with `query_wait_timeout`; the
+ # query never reached Postgres, so retrying it is safe and avoids failing the whole
+ # import activity (and redoing the batch pull) over a momentary blip.
+ update = MagicMock(side_effect=[OperationalError("query_wait_timeout"), None])
+ queryset = MagicMock(update=update)
+ logger = MagicMock(adebug=AsyncMock())
+
+ with (
+ patch(f"{_LOAD_MODULE}.ExternalDataJob.objects.filter", return_value=queryset),
+ patch(f"{_DB_RETRY_MODULE}.close_old_connections") as close,
+ patch(f"{_DB_RETRY_MODULE}.time.sleep") as sleep,
+ ):
+ await update_job_row_count("job-1", 5, logger)
+
+ assert update.call_count == 2
+ close.assert_called_once()
+ sleep.assert_called_once_with(2)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 77248b7f4894..6085c979d702 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -29,6 +29,9 @@ from products.warehouse_sources.backend.models.external_data_schema import (
)
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (
+ retry_on_operational_error,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
build_table_name,
resolve_table_and_folder_names,
@@ -114,11 +117,14 @@ class PipelineInputs:
async def update_last_synced_at(job_id: str, schema_id: str, team_id: int) -> None:
@database_sync_to_async_pool
+ @retry_on_operational_error
def _update():
job = ExternalDataJob.objects.get(pk=job_id)
schema = ExternalDataSchema.objects.exclude(deleted=True).get(id=schema_id, team_id=team_id)
schema.last_synced_at = job.created_at
- schema.save()
+ # Pipeline-internal bookkeeping, not a user edit — skip_activity_log avoids the extra
+ # `_get_before_update` SELECT that also needs a pooler connection (see save()).
+ schema.save(skip_activity_log=True)
await _update()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
index 38c308bae1c9..e40413b20b42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
@@ -1,9 +1,10 @@
import uuid
+import pytest
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
-from django.db import transaction
+from django.db import OperationalError, transaction
from parameterized import parameterized
@@ -16,7 +17,13 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers
build_table_name,
resolve_table_and_folder_names,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import merge_columns
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
+ merge_columns,
+ update_last_synced_at,
+)
+
+_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"
+_DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"
class TestResolveTableAndFolderNames:
@@ -271,3 +278,31 @@ class TestRegisterCDCCompanionTable(BaseTest):
deleted=False,
)
assert companions.count() == 0
+
+
+class TestUpdateLastSyncedAt:
+ @pytest.mark.asyncio
+ async def test_retries_transient_query_wait_timeout_then_succeeds(self):
+ # A saturated pgbouncer pool can reject either read with `query_wait_timeout` before the
+ # query ever reaches Postgres, so retrying the whole lookup+save is safe and avoids
+ # failing the whole import activity over a momentary blip.
+ job = MagicMock()
+ get_job = MagicMock(side_effect=[OperationalError("query_wait_timeout"), job])
+ schema = MagicMock()
+ get_schema = MagicMock(return_value=schema)
+
+ with (
+ patch(f"{_PIPELINE_SYNC_MODULE}.ExternalDataJob.objects.get", get_job),
+ patch(
+ f"{_PIPELINE_SYNC_MODULE}.ExternalDataSchema.objects.exclude", return_value=MagicMock(get=get_schema)
+ ),
+ patch(f"{_DB_RETRY_MODULE}.close_old_connections") as close,
+ patch(f"{_DB_RETRY_MODULE}.time.sleep") as sleep,
+ ):
+ await update_last_synced_at(job_id="job-1", schema_id="schema-1", team_id=1)
+
+ assert get_job.call_count == 2
+ assert schema.last_synced_at == job.created_at
+ schema.save.assert_called_once_with(skip_activity_log=True)
+ close.assert_called_once()
+ sleep.assert_called_once_with(2)
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 376226596d1c..79d5915665ba 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -205,6 +205,54 @@ class TestExternalDataSchemaActivityLogging(BaseTest):
schema.refresh_from_db()
assert schema.incremental_field_last_value == 42
+ def test_set_partitioning_enabled_save_skips_activity_log(self) -> None:
+ schema = self._create(sync_type_config={})
+ model_activity_signal.connect(self._signal_handler, sender=ExternalDataSchema)
+ try:
+ schema.set_partitioning_enabled(
+ partitioning_keys=["id"],
+ partition_count=10,
+ partition_size=None,
+ partition_mode="md5",
+ partition_format=None,
+ )
+ assert not self.signal_received
+ finally:
+ model_activity_signal.disconnect(self._signal_handler, sender=ExternalDataSchema)
+ schema.refresh_from_db()
+ assert schema.sync_type_config["partitioning_enabled"] is True
+
+ def test_stage_incremental_field_value_save_skips_activity_log(self) -> None:
+ schema = self._create(
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={"incremental_field_type": IncrementalFieldType.Integer},
+ )
+ model_activity_signal.connect(self._signal_handler, sender=ExternalDataSchema)
+ try:
+ schema.stage_incremental_field_value("run-1", 42)
+ assert not self.signal_received
+ finally:
+ model_activity_signal.disconnect(self._signal_handler, sender=ExternalDataSchema)
+ schema.refresh_from_db()
+ assert schema.sync_type_config["incremental_staged"]["last_value"] == 42
+
+ def test_promote_staged_incremental_values_save_skips_activity_log(self) -> None:
+ schema = self._create(
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={
+ "incremental_field_type": IncrementalFieldType.Integer,
+ "incremental_staged": {"run_uuid": "run-1", "last_value": 42},
+ },
+ )
+ model_activity_signal.connect(self._signal_handler, sender=ExternalDataSchema)
+ try:
+ assert schema.promote_staged_incremental_values("run-1")
+ assert not self.signal_received
+ finally:
+ model_activity_signal.disconnect(self._signal_handler, sender=ExternalDataSchema)
+ schema.refresh_from_db()
+ assert schema.sync_type_config["incremental_field_last_value"] == 42
+
def test_bookkeeping_save_raises_instead_of_resurrecting_deleted_row(self) -> None:
# Source (and its schema, via CASCADE) deleted concurrently with a sync still holding a
# stale in-memory schema reference. Without force_update, Django's UUID-pk insert fallback