: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): run queue partition database work off the event loop (#105241)
Daniel RCbaa8f1c54c49
diff --git a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.pyindex 8347c5ce853f..74699ea6f853 100644--- a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py+++ b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py@@ -2,6 +2,7 @@from __future__ import annotations+import threadingfrom contextlib import contextmanagerfrom datetime import UTC, date, datetimefrom types import TracebackType@@ -15,6 +16,7 @@ from unittest.mock import MagicMock, call, patchfrom django.db import connectionimport psycopg+from asgiref.sync import sync_to_asyncfrom psycopg.conninfo import make_conninfofrom posthog.temporal.warehouse_sources_queue_partition_management import activities as activities_module@@ -321,6 +323,7 @@ class _FakePgConn:self.denied_drops = denied_dropsself.dropped: list[str] = []self.deleted: list[tuple[str, datetime]] = []+ self.execute_threads: set[int] = set()def __enter__(self) -> _FakePgConn:return self@@ -329,6 +332,7 @@ class _FakePgConn:return Falsedef execute(self, sql: Any, params: Any = None) -> MagicMock:+ self.execute_threads.add(threading.get_ident())cursor = MagicMock()cursor.fetchall.return_value = []cursor.rowcount = 0@@ -507,6 +511,21 @@ async def test_activity_terminalizes_only_sourcebatch_partitions_then_drops(actiassert result["success"] is True+async def test_activity_runs_queue_database_statements_on_a_pool_thread(activity_environment) -> None:+ shared_thread_sensitive_ident = await sync_to_async(threading.get_ident)()++ with (+ _patched_pg({"sourcebatch": [OLD_BATCH_PART]}) as conn,+ _patched_s3([]),+ patch.object(activities_module, "_terminalize_stranded_runs"),+ ):+ await activity_environment.run(manage_warehouse_sources_queue_partitions)++ assert conn.dropped == [OLD_BATCH_PART]+ assert conn.execute_threads.isdisjoint({threading.get_ident(), shared_thread_sensitive_ident})++@pytest.mark.asyncioasync def test_activity_keeps_partition_when_terminalization_fails(activity_environment) -> None:partitions = {diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex af884d753221..c91276aef45c 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -10,7 +10,9 @@ import psycopgimport requestsimport structlogimport temporalio.activity-from asgiref.sync import sync_to_async++from posthog.dataclasses import frozen+from posthog.sync import database_sync_to_async_poollogger = structlog.get_logger(__name__)@@ -40,15 +42,52 @@ class PartitionResult:return len(self.errors) == 0+@frozen+class _PartitionChanges:+ ensured: list[str]+ dropped: list[str]++@temporalio.activity.defnasync def manage_warehouse_sources_queue_partitions() -> dict:+ errors: list[str] = []+ today = datetime.now(UTC).date()++ # The connection sets no lock_timeout, so partition DDL can wait on a lock for an unbounded time.+ # Run the database work on the general thread pool so that the wait blocks neither the worker's+ # event loop nor the single thread shared by all thread-sensitive work in the process.+ changes = await database_sync_to_async_pool(_manage_database_partitions)(today, errors)++ s3_deleted = _cleanup_old_s3_extractions(today, errors)++ result = PartitionResult(ensured=changes.ensured, dropped=changes.dropped, errors=errors, s3_deleted=s3_deleted)++ logger.info(+ "Partition management completed",+ ensured_count=len(result.ensured),+ dropped_count=len(result.dropped),+ s3_deleted_count=len(s3_deleted),+ error_count=len(errors),+ success=result.success,+ )++ if not result.success:+ _send_slack_failure(errors)++ return {+ "ensured": result.ensured,+ "dropped": result.dropped,+ "s3_deleted": result.s3_deleted,+ "errors": result.errors,+ "success": result.success,+ }+++def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionChanges:ensured: list[str] = []dropped: list[str] = []- errors: list[str] = []with psycopg.Connection.connect(_partition_ddl_database_url(), autocommit=True) as conn:- today = datetime.now(UTC).date()-for table in PARTITIONED_TABLES:for offset in range(PARTITIONS_AHEAD):d = today + timedelta(days=offset)@@ -77,7 +116,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:).fetchall():partition_name = row[0]if partition_name.endswith("_default"):- await sync_to_async(_expire_default_partition_rows)(conn, table, partition_name, cutoff, errors)+ _expire_default_partition_rows(conn, table, partition_name, cutoff, errors)continuesuffix = partition_name.rsplit("_", 1)[-1]try:@@ -87,7 +126,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:if partition_date < cutoff:if table == "sourcebatch":try:- await sync_to_async(_terminalize_stranded_runs)(conn, partition_name)+ _terminalize_stranded_runs(conn, partition_name)except Exception as e:# Keep the partition as evidence while the alert is live;# partitions are daily and small, so retrying tomorrow is cheap.@@ -98,7 +137,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:)continuetry:- await sync_to_async(_drop_partition)(conn, partition_name)+ _drop_partition(conn, partition_name)dropped.append(partition_name)except Exception as e:errors.append(f"Failed to drop {partition_name}: {e}")@@ -106,29 +145,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:_verify_partitions(conn, today, errors)- s3_deleted = _cleanup_old_s3_extractions(today, errors)-- result = PartitionResult(ensured=ensured, dropped=dropped, errors=errors, s3_deleted=s3_deleted)-- logger.info(- "Partition management completed",- ensured_count=len(ensured),- dropped_count=len(dropped),- s3_deleted_count=len(s3_deleted),- error_count=len(errors),- success=result.success,- )-- if not result.success:- _send_slack_failure(errors)-- return {- "ensured": result.ensured,- "dropped": result.dropped,- "s3_deleted": result.s3_deleted,- "errors": result.errors,- "success": result.success,- }+ return _PartitionChanges(ensured=ensured, dropped=dropped)def _partition_ddl_database_url() -> str: