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): recover from a stale db connection when writing warehouse column statistics (#83884)

Tom Owers5e3fa9b4a3ea
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 4424638db9c1..bda632aafe38 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
@@ -19,6 +19,8 @@ import dataclasses
from datetime import timedelta
from typing import Any
+from django.conf import settings
+from django.db import InterfaceError, OperationalError, close_old_connections
from django.utils import timezone
import structlog
@@ -237,8 +239,20 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[st
row_count, stats_by_column = _aggregate_add_action_stats(add_actions, columns)
- for column_name, stat in stats_by_column.items():
- _upsert_statistics(team, table, column_name, row_count, stat, delta_version)
+ try:
+ for column_name, stat in stats_by_column.items():
+ _upsert_statistics(team, table, column_name, row_count, stat, delta_version)
+ except (OperationalError, InterfaceError):
+ # The Delta-log read above can run long enough for the Postgres connection opened by the
+ # earlier metadata queries (team/schema/existing-stats) to go stale — server restart, proxy
+ # idle-close — before these writes run. Django only clears a stale connection at thread
+ # entry/exit, not mid-call, so the first write here is the first thing to notice. Retry once
+ # after reconnecting rather than failing the whole activity and forcing Temporal to redo the
+ # Delta-log read just to redo a handful of upserts.
+ if not settings.TEST:
+ close_old_connections()
+ for column_name, stat in stats_by_column.items():
+ _upsert_statistics(team, table, column_name, row_count, stat, delta_version)
log.info("warehouse_statistics.done", columns=len(stats_by_column), row_count=row_count)
emit_completed("done", columns=len(stats_by_column), row_count=row_count, delta_version=delta_version)
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 e3f879ae0b67..f8b7b54ed94e 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
@@ -195,6 +195,25 @@ class TestComputeTableStatisticsSync:
assert stat.computed_for_delta_version == 12
assert stat.column_type == "Int64"
+ def test_recovers_from_stale_connection_during_write(self) -> None:
+ # The Delta-log read can run long enough for the pooled connection opened by the earlier
+ # metadata queries to go stale before the write loop runs, raising OperationalError on the
+ # first upsert. The retry-after-reconnect must recover instead of failing the whole activity.
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ add_actions = pa.table({"num_records": [10], "null_count.amount": [1], "min.amount": [5], "max.amount": [9]})
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions)),
+ patch.object(
+ comp, "_upsert_statistics", side_effect=[OperationalError("server conn crashed?"), None]
+ ) as mock_upsert,
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "done"
+ assert mock_upsert.call_count == 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