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): evict stale DB connections before ducklake ORM lookups (#73128)

Tom Owers38d38992c46e
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
index 3d5711f75daa..560d081cfc4f 100644
--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
@@ -6,6 +6,7 @@ import dataclasses
from urllib.parse import urlparse
from django.conf import settings
+from django.db import close_old_connections
import duckdb
import deltalake
@@ -292,6 +293,11 @@ def copy_data_imports_to_ducklake_activity(inputs: DuckLakeCopyDataImportsActivi
"""Copy a single data imports schema's Delta snapshot into DuckLake."""
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind(model_label=inputs.model.model_label, job_id=inputs.job_id)
+ # This activity runs in a long-lived worker thread that never goes through Django's
+ # request/response cycle, so a connection killed by the DB/proxy (e.g. after
+ # CONN_MAX_AGE) is never detected and closed before reuse.
+ if not settings.TEST:
+ close_old_connections()
heartbeater = HeartbeaterSync(details=("ducklake_copy", inputs.model.model_label), logger=logger)
with heartbeater:
@@ -378,6 +384,9 @@ class DuckLakeDataImportsStagingCleanupInputs:
def cleanup_data_imports_staging_activity(inputs: DuckLakeDataImportsStagingCleanupInputs) -> None:
"""Clean up staged Delta files after successful verification."""
bind_contextvars(team_id=inputs.team_id)
+ # Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity.
+ if not settings.TEST:
+ close_old_connections()
server = get_duckgres_server_by_team_org(inputs.team_id)
if server is None:
return
@@ -454,6 +463,9 @@ def verify_data_imports_ducklake_copy_activity(
"""Run configured verification queries to ensure the copy matches the source."""
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind(model_label=inputs.model.model_label, job_id=inputs.job_id)
+ # Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity.
+ if not settings.TEST:
+ close_old_connections()
if not inputs.model.verification_queries:
logger.info("No DuckLake verification queries configured - skipping")
diff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
index 884783afe955..90acf6a4e74d 100644
--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
@@ -6,6 +6,7 @@ import pytest
from unittest.mock import MagicMock
from django.conf import settings
+from django.test import override_settings
import temporalio.worker
import temporalio.converter
@@ -467,6 +468,11 @@ def test_copy_data_imports_to_ducklake_activity_via_duckdb(monkeypatch):
"posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.HeartbeaterSync",
MagicMock(return_value=mock_heartbeater),
)
+ mock_close_old_connections = MagicMock()
+ monkeypatch.setattr(
+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.close_old_connections",
+ mock_close_old_connections,
+ )
monkeypatch.setattr(
"posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.is_dev_mode",
MagicMock(return_value=True),
@@ -514,8 +520,14 @@ def test_copy_data_imports_to_ducklake_activity_via_duckdb(monkeypatch):
)
inputs = DuckLakeCopyDataImportsActivityInputs(team_id=1, job_id="job-123", model=metadata)
- copy_data_imports_to_ducklake_activity(inputs)
+ # TEST=False: the close_old_connections() call is skipped under settings.TEST (matching
+ # database_sync_to_async's convention) so it never trips pytest-django's db-access guard
+ # in tests that don't need the database; override it here to prove the call still fires
+ # outside tests, i.e. in the real long-lived worker thread.
+ with override_settings(TEST=False):
+ copy_data_imports_to_ducklake_activity(inputs)
+ mock_close_old_connections.assert_called_once()
mock_configure_connection.assert_called_once_with(mock_conn)
mock_ensure_bucket.assert_called_once_with(config={"DUCKLAKE_BUCKET": "ducklake-dev"}, team_id=1)
mock_attach_catalog.assert_called_once_with(mock_conn, {"DUCKLAKE_BUCKET": "ducklake-dev"}, alias="ducklake")
@@ -617,6 +629,11 @@ def test_verify_data_imports_ducklake_copy_activity_returns_empty_when_no_querie
"posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.HeartbeaterSync",
MagicMock(return_value=mock_heartbeater),
)
+ mock_close_old_connections = MagicMock()
+ monkeypatch.setattr(
+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.close_old_connections",
+ mock_close_old_connections,
+ )
metadata = DuckLakeCopyDataImportsMetadata(
model_label="postgres_customers",
@@ -630,9 +647,14 @@ def test_verify_data_imports_ducklake_copy_activity_returns_empty_when_no_querie
)
inputs = DuckLakeCopyDataImportsActivityInputs(team_id=1, job_id="job-123", model=metadata)
- results = verify_data_imports_ducklake_copy_activity(inputs)
+ # TEST=False: see the comment in test_copy_data_imports_to_ducklake_activity_via_duckdb.
+ with override_settings(TEST=False):
+ results = verify_data_imports_ducklake_copy_activity(inputs)
assert results == []
+ # Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity:
+ # this must run even on the early-return path, before any DB access is attempted.
+ mock_close_old_connections.assert_called_once()
def test_verify_data_imports_ducklake_copy_activity_uses_duckdb_in_dev(monkeypatch):
@@ -969,6 +991,23 @@ def test_verify_data_imports_ducklake_copy_activity_tolerance_comparison(monkeyp
assert results[1].passed is False
+def test_cleanup_data_imports_staging_activity_closes_stale_connections_before_querying(monkeypatch):
+ """Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity:
+ a connection killed by the DB/proxy is never detected and closed before reuse
+ unless the activity does it itself."""
+ mock_close_old_connections = MagicMock()
+ monkeypatch.setattr(ducklake_module, "close_old_connections", mock_close_old_connections)
+ monkeypatch.setattr(ducklake_module, "get_duckgres_server_by_team_org", MagicMock(return_value=None))
+
+ inputs = DuckLakeDataImportsStagingCleanupInputs(team_id=1, staging_uri="s3://bucket/__posthog_staging/team_1")
+
+ # TEST=False: see the comment in test_copy_data_imports_to_ducklake_activity_via_duckdb.
+ with override_settings(TEST=False):
+ ducklake_module.cleanup_data_imports_staging_activity(inputs)
+
+ mock_close_old_connections.assert_called_once()
+
+
_DUCKGRES_CURSOR_DESCRIPTION = [_FakeColumn("id", 20), _FakeColumn("name", 25)]
_DUCKGRES_EXPECTED_SCHEMA = [("id", "20"), ("name", "25")]
_DUCKDB_CURSOR_DESCRIPTION = [
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
index 853351dfed0d..f789af1b6ed8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
@@ -15,6 +15,7 @@ from prometheus_client import Gauge
from posthog.exceptions_capture import capture_exception
from posthog.models import DuckgresSinkSchemaState
+from posthog.sync import database_sync_to_async_pool
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
MAX_ATTEMPTS,
@@ -159,7 +160,10 @@ class DuckgresBatchConsumerAdapter:
try:
first_resolution = self._team_ids_fetched_at is None
previous = self._team_ids
- enablement = await sync_to_async(duckgres_sink_enablement, thread_sensitive=False)()
+ # database_sync_to_async_pool (not a bare sync_to_async) so a connection killed by
+ # the DB/proxy since the last refresh gets closed and reopened before this query,
+ # instead of surfacing as "the connection is closed" OperationalErrors.
+ enablement = await database_sync_to_async_pool(duckgres_sink_enablement)()
self._team_ids = None if enablement is None else enablement.team_ids
self._team_org_budgets = [] if enablement is None else enablement.team_org_budgets
self._team_ids_fetched_at = now
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
index b59828cfa148..81ccbd863bf4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
@@ -20,6 +20,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DuckgresBatchConsumerAdapter,
DuckgresConsumerConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (
+ duckgres_sink_enablement,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
PendingBatch,
)
@@ -226,6 +229,21 @@ class TestDuckgresProcessSingle:
class TestDuckgresEnablementGating:
+ @pytest.mark.asyncio
+ async def test_enabled_team_ids_refresh_uses_connection_safe_wrapper(self):
+ """The refresh crosses from the asyncio poll loop into a worker thread; a bare
+ sync_to_async never recovers a connection killed by the DB/proxy since the last
+ refresh, so this must go through database_sync_to_async_pool instead."""
+ adapter = DuckgresBatchConsumerAdapter()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.database_sync_to_async_pool",
+ ) as mock_wrapper:
+ mock_wrapper.return_value = AsyncMock(return_value=None)
+ await adapter._enabled_team_ids()
+
+ mock_wrapper.assert_called_once_with(duckgres_sink_enablement)
+
@pytest.mark.asyncio
async def test_fetch_returns_empty_without_querying_when_no_teams_enabled(self):
adapter = DuckgresBatchConsumerAdapter()