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): retry the team lookup after a postgres deadlock (#100760)

Tom Owers86a3b988f44f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
index fdd42d70079e..47795e0b5889 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
@@ -41,6 +41,9 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.models.util import clean_type
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (
+ retry_on_operational_error,
+)
logger = structlog.get_logger(__name__)
@@ -164,6 +167,11 @@ def _most_recent_computed_at(existing: dict[str, WarehouseColumnStatistics]) ->
return max(times) if times else None
+@retry_on_operational_error
+def _get_team(team_id: int) -> Team:
+ return Team.objects.select_related("organization").only("id", "uuid", "organization_id").get(id=team_id)
+
+
def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str, Any]:
"""Compute and persist per-column statistics for one warehouse table. Safe to re-run."""
# Lazy: DeltaTableRef drags deltalake/pyarrow/dlt — keep them off the flag-check import path that
@@ -176,7 +184,9 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[st
log = logger.bind(team_id=team_id, schema_id=str(schema_id))
- team = Team.objects.select_related("organization").only("id", "uuid", "organization_id").get(id=team_id)
+ # A plain read, so it's safe to retry outright on the Team/Organization join losing a
+ # Postgres deadlock race against an unrelated writer of either table.
+ team = _get_team(team_id)
event_props: dict[str, Any] = {"schema_id": str(schema_id)}
def emit_completed(status: str, **props: Any) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
index f8b7b54ed94e..678058c16fea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
@@ -2,6 +2,7 @@ import json
import uuid
import datetime as dt
from decimal import Decimal
+from typing import Any
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -214,6 +215,37 @@ class TestComputeTableStatisticsSync:
assert result["status"] == "done"
assert mock_upsert.call_count == 2
+ def test_recovers_from_deadlock_on_team_lookup(self) -> None:
+ # The Team/Organization join at the top of the activity can lose a Postgres deadlock race
+ # against an unrelated writer of either table. It's a plain read, so retrying it must
+ # recover instead of failing the whole activity (and reaching error tracking) over a race
+ # that clears on its own.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ add_actions = pa.table({"num_records": [1], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})
+ real_select_related = comp.Team.objects.select_related
+ lookups: list[tuple[Any, ...]] = []
+
+ def select_related_losing_first_deadlock(*fields: Any) -> Any:
+ lookups.append(fields)
+ if len(lookups) == 1:
+ raise OperationalError("deadlock detected")
+ return real_select_related(*fields)
+
+ with (
+ patch.object(comp.Team.objects, "select_related", side_effect=select_related_losing_first_deadlock),
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions)),
+ patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry.time.sleep"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry.close_old_connections"
+ ),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "done"
+ assert len(lookups) == 2
+
def test_job_reuses_prefetched_schema_to_avoid_lazy_query(self) -> None:
# job is fetched without select_related("schema"), so job.folder_path() (which reads
# job.schema.source.source_type) would otherwise fire a lazy SELECT on a pooled connection a