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): order postgres schema updates to avoid deadlocks (#98780)

Tom Owers93ab23ac2f0c
diff --git a/products/data_warehouse/backend/postgres_helpers.py b/products/data_warehouse/backend/postgres_helpers.py
index 552437f3b0e9..0d469b649144 100644
--- a/products/data_warehouse/backend/postgres_helpers.py
+++ b/products/data_warehouse/backend/postgres_helpers.py
@@ -185,6 +185,7 @@ def reconcile_postgres_schemas(
)
schema_models_by_location.setdefault(location, schema_model)
+ resolved_pairs: list[tuple[SourceSchema, ExternalDataSchema]] = []
for source_schema in source_schemas:
matched: ExternalDataSchema | None = schema_models.get(source_schema.name)
if matched is None:
@@ -198,9 +199,16 @@ def reconcile_postgres_schemas(
default_schema=default_schema,
)
matched = schema_models_by_location.get(location)
- if matched is None:
- continue
+ if matched is not None:
+ resolved_pairs.append((source_schema, matched))
+
+ # Process in a stable row-id order rather than `source_schemas`' order, which follows the
+ # source database's own (unordered) catalog query. Two concurrent refreshes updating an
+ # overlapping set of these rows could otherwise take their row locks in different sequences
+ # and deadlock; a consistent order makes one call simply wait behind the other.
+ resolved_pairs.sort(key=lambda pair: pair[1].id)
+ for source_schema, matched in resolved_pairs:
resolved_catalog, resolved_schema, resolved_table = get_postgres_source_location(
schema_name=source_schema.name,
schema_metadata={
diff --git a/products/data_warehouse/backend/test/test_postgres_helpers.py b/products/data_warehouse/backend/test/test_postgres_helpers.py
index 1319689b3b89..ca1d9a06342f 100644
--- a/products/data_warehouse/backend/test/test_postgres_helpers.py
+++ b/products/data_warehouse/backend/test/test_postgres_helpers.py
@@ -1,10 +1,17 @@
+import uuid
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
from parameterized import parameterized
-from products.data_warehouse.backend.postgres_helpers import get_postgres_source_location
+from products.data_warehouse.backend.postgres_helpers import get_postgres_source_location, reconcile_postgres_schemas
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.source_management import (
filter_columns_by_enabled_columns,
filter_dwh_columns_by_enabled_columns,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
class TestGetPostgresSourceLocation:
@@ -73,3 +80,52 @@ class TestFilterDwhColumnsByEnabledColumns:
def test_empty_keeps_only_pks_and_incremental(self) -> None:
result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, [], ["id"], incremental_field="updated_at")
assert set(result.keys()) == {"id", "updated_at"}
+
+
+class TestReconcilePostgresSchemasLockOrder(APIBaseTest):
+ def test_updates_rows_in_ascending_id_order_regardless_of_input_order(self) -> None:
+ # Two concurrent refreshes touching an overlapping set of these rows must take their row
+ # locks in the same order, or they can deadlock (seen in production: "deadlock detected
+ # ... while updating tuple ... in relation posthog_externaldataschema"). The source
+ # database's own catalog query doesn't guarantee row order, so `source_schemas` can arrive
+ # in a different order on each call — reconcile_postgres_schemas must impose its own
+ # stable order rather than following it.
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Postgres",
+ created_by=self.user,
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},
+ )
+ schema_a = ExternalDataSchema.objects.create(
+ team_id=self.team.pk, source_id=source.pk, name="table_a", should_sync=True
+ )
+ schema_b = ExternalDataSchema.objects.create(
+ team_id=self.team.pk, source_id=source.pk, name="table_b", should_sync=True
+ )
+ assert schema_a.id < schema_b.id
+
+ # Discovery order is the reverse of row-id order.
+ source_schemas = [
+ SourceSchema(
+ name="table_b", supports_incremental=False, supports_append=False, columns=[("id", "integer", False)]
+ ),
+ SourceSchema(
+ name="table_a", supports_incremental=False, supports_append=False, columns=[("id", "integer", False)]
+ ),
+ ]
+
+ saved_names: list[str] = []
+ original_save = ExternalDataSchema.save
+
+ def _tracking_save(self: ExternalDataSchema, *args, **kwargs):
+ saved_names.append(self.name)
+ return original_save(self, *args, **kwargs)
+
+ with patch.object(ExternalDataSchema, "save", _tracking_save):
+ reconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=self.team.pk)
+
+ assert saved_names == ["table_a", "table_b"]