: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
feat(ws): add Temporal job for warehouse sources queue partition management (#57143)
estefania41049ca43415
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex da6f5ee56884..968b885a712a 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -152,6 +152,10 @@ from posthog.temporal.usage_reports import (ACTIVITIES as USAGE_REPORTS_ACTIVITIES,WORKFLOWS as USAGE_REPORTS_WORKFLOWS,)+from posthog.temporal.warehouse_sources_queue_partition_management import (+ ACTIVITIES as WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,+ WORKFLOWS as WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,+)from posthog.temporal.weekly_digest import (ACTIVITIES as WEEKLY_DIGEST_ACTIVITIES,WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,@@ -218,7 +222,8 @@ _task_queue_specs = [+ SYNC_PERSON_DISTINCT_IDS_WORKFLOWS+ EXPERIMENTS_WORKFLOWS+ CLEANUP_PROPDEFS_WORKFLOWS- + INGESTION_ACCEPTANCE_TEST_WORKFLOWS,+ + INGESTION_ACCEPTANCE_TEST_WORKFLOWS+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ USAGE_REPORTS_ACTIVITIES@@ -230,7 +235,8 @@ _task_queue_specs = [+ SYNC_PERSON_DISTINCT_IDS_ACTIVITIES+ EXPERIMENTS_ACTIVITIES+ CLEANUP_PROPDEFS_ACTIVITIES- + INGESTION_ACCEPTANCE_TEST_ACTIVITIES,+ + INGESTION_ACCEPTANCE_TEST_ACTIVITIES+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,),(settings.HEALTH_CHECK_TASK_QUEUE,diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 1c72ec95ed2a..889eb93a9e7a 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -574,3 +574,8 @@ PATCH_EVENT_LIST_MAX_OFFSET_PER_TEAM: set[int] = get_from_env()CLICKHOUSE_EVENT_LIST_MAX_THREADS: int = get_from_env("CLICKHOUSE_EVENT_LIST_MAX_THREADS", 50, type_cast=int)++WAREHOUSE_SOURCES_DATABASE_URL: str = os.getenv("WAREHOUSE_SOURCES_DATABASE_URL", "")+WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL: str = os.getenv(+ "WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL", ""+)diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex e7b4e3c865c8..d4c9f034113d 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -70,6 +70,9 @@ from posthog.temporal.session_replay.summarization_sweep.reconciler import (create_summarization_sweep_reconciler_schedule,)from posthog.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs+from posthog.temporal.warehouse_sources_queue_partition_management.schedule import (+ create_warehouse_sources_queue_partition_management_schedule,+)from posthog.temporal.weekly_digest.types import WeeklyDigestInputfrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInput@@ -553,6 +556,7 @@ schedules = [create_experiment_saved_metrics_schedules,create_all_realtime_cohort_calculation_schedules,create_ingestion_acceptance_test_schedule,+ create_warehouse_sources_queue_partition_management_schedule,create_health_check_schedules,create_conversations_signals_coordinator_schedule,create_wa_weekly_digest_schedule,diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/__init__.py b/posthog/temporal/warehouse_sources_queue_partition_management/__init__.pynew file mode 100644index 000000000000..f4e2d5968059--- /dev/null+++ b/posthog/temporal/warehouse_sources_queue_partition_management/__init__.py@@ -0,0 +1,14 @@+from posthog.temporal.warehouse_sources_queue_partition_management.activities import (+ manage_warehouse_sources_queue_partitions,+)+from posthog.temporal.warehouse_sources_queue_partition_management.workflows import (+ WarehouseSourcesQueuePartitionManagementWorkflow,+)++WORKFLOWS = [WarehouseSourcesQueuePartitionManagementWorkflow]+ACTIVITIES = [manage_warehouse_sources_queue_partitions]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+]diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pynew file mode 100644index 000000000000..a6aa2dda1bbb--- /dev/null+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -0,0 +1,149 @@+from __future__ import annotations++from dataclasses import dataclass+from datetime import date, timedelta++from django.conf import settings++import psycopg+import requests+import structlog+import temporalio.activity++logger = structlog.get_logger(__name__)++PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus"]+PARTITIONS_AHEAD = 7+RETENTION_DAYS = 7+++@dataclass(frozen=True, slots=True)+class PartitionResult:+ ensured: list[str]+ dropped: list[str]+ errors: list[str]++ @property+ def success(self) -> bool:+ return len(self.errors) == 0+++async def manage_warehouse_sources_queue_partitions() -> dict:+ database_url: str = settings.WAREHOUSE_SOURCES_DATABASE_URL+ ensured: list[str] = []+ dropped: list[str] = []+ errors: list[str] = []++ with psycopg.Connection.connect(database_url, autocommit=True) as conn:+ today = date.today()++ for table in PARTITIONED_TABLES:+ for offset in range(PARTITIONS_AHEAD):+ d = today + timedelta(days=offset)+ partition_name = f"{table}_{d.strftime('%Y%m%d')}"+ try:+ conn.execute(+ f"CREATE TABLE IF NOT EXISTS {partition_name} "+ f"PARTITION OF {table} "+ f"FOR VALUES FROM ('{d.isoformat()}') TO ('{(d + timedelta(days=1)).isoformat()}')"+ )+ ensured.append(partition_name)+ except Exception as e:+ errors.append(f"Failed to create {partition_name}: {e}")+ logger.exception("Failed to create partition", partition=partition_name)++ cutoff = today - timedelta(days=RETENTION_DAYS)+ for table in PARTITIONED_TABLES:+ for row in conn.execute(+ """+ SELECT inhrelid::regclass::text AS partition_name+ FROM pg_inherits+ WHERE inhparent = %s::regclass+ ORDER BY inhrelid::regclass::text+ """,+ [table],+ ).fetchall():+ partition_name = row[0]+ if partition_name.endswith("_default"):+ continue+ suffix = partition_name.rsplit("_", 1)[-1]+ try:+ partition_date = date(int(suffix[:4]), int(suffix[4:6]), int(suffix[6:8]))+ except (ValueError, IndexError):+ continue+ if partition_date < cutoff:+ try:+ conn.execute(f"DROP TABLE IF EXISTS {partition_name}")+ dropped.append(partition_name)+ except Exception as e:+ errors.append(f"Failed to drop {partition_name}: {e}")+ logger.exception("Failed to drop partition", partition=partition_name)++ _verify_partitions(conn, today, errors)++ result = PartitionResult(ensured=ensured, dropped=dropped, errors=errors)++ logger.info(+ "Partition management completed",+ ensured_count=len(ensured),+ dropped_count=len(dropped),+ error_count=len(errors),+ success=result.success,+ )++ if not result.success:+ _send_slack_failure(errors)++ return {"ensured": result.ensured, "dropped": result.dropped, "errors": result.errors, "success": result.success}+++def _verify_partitions(conn: psycopg.Connection, today: date, errors: list[str]) -> None:+ for table in PARTITIONED_TABLES:+ existing = set()+ for row in conn.execute(+ """+ SELECT inhrelid::regclass::text AS partition_name+ FROM pg_inherits+ WHERE inhparent = %s::regclass+ """,+ [table],+ ).fetchall():+ existing.add(row[0])++ for offset in range(PARTITIONS_AHEAD):+ d = today + timedelta(days=offset)+ expected = f"{table}_{d.strftime('%Y%m%d')}"+ if expected not in existing:+ errors.append(f"Partition {expected} missing after creation attempt")+++def _send_slack_failure(errors: list[str]) -> None:+ webhook_url = settings.WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL+ if not webhook_url:+ logger.warning("No Slack webhook configured for partition management alerts")+ return++ error_text = "\n".join(f"- {e}" for e in errors[:10])+ blocks = [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": ":rotating_light: *Warehouse sources queue partition management failed*",+ },+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": f"```{error_text}```",+ },+ },+ ]++ try:+ response = requests.post(webhook_url, json={"blocks": blocks}, timeout=10)+ response.raise_for_status()+ except requests.RequestException as e:+ logger.warning("Failed to send Slack notification", error=str(e))diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/schedule.py b/posthog/temporal/warehouse_sources_queue_partition_management/schedule.pynew file mode 100644index 000000000000..75b6483ce815--- /dev/null+++ b/posthog/temporal/warehouse_sources_queue_partition_management/schedule.py@@ -0,0 +1,44 @@+import uuid++from django.conf import settings++from temporalio import common+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleCalendarSpec,+ ScheduleRange,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule+from posthog.temporal.warehouse_sources_queue_partition_management.types import PartitionManagementInput++SCHEDULE_ID = "warehouse-sources-queue-partition-management-schedule"+WORKFLOW_NAME = "warehouse-sources-queue-partition-management"+++async def create_warehouse_sources_queue_partition_management_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ WORKFLOW_NAME,+ PartitionManagementInput(),+ id=str(uuid.uuid4()),+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ ),+ spec=ScheduleSpec(+ calendars=[+ ScheduleCalendarSpec(+ comment="Daily at 8 AM UTC",+ hour=[ScheduleRange(start=8, end=8)],+ )+ ]+ ),+ )++ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/types.py b/posthog/temporal/warehouse_sources_queue_partition_management/types.pynew file mode 100644index 000000000000..a2a1e094fabc--- /dev/null+++ b/posthog/temporal/warehouse_sources_queue_partition_management/types.py@@ -0,0 +1,5 @@+from pydantic import BaseModel+++class PartitionManagementInput(BaseModel):+ passdiff --git a/posthog/temporal/warehouse_sources_queue_partition_management/workflows.py b/posthog/temporal/warehouse_sources_queue_partition_management/workflows.pynew file mode 100644index 000000000000..823761b4fa43--- /dev/null+++ b/posthog/temporal/warehouse_sources_queue_partition_management/workflows.py@@ -0,0 +1,27 @@+from datetime import timedelta++import temporalio.workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++with temporalio.workflow.unsafe.imports_passed_through():+ from posthog.temporal.warehouse_sources_queue_partition_management.activities import (+ manage_warehouse_sources_queue_partitions,+ )+ from posthog.temporal.warehouse_sources_queue_partition_management.types import PartitionManagementInput++[email protected](name="warehouse-sources-queue-partition-management")+class WarehouseSourcesQueuePartitionManagementWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> PartitionManagementInput:+ return PartitionManagementInput.model_validate_json(inputs[0]) if inputs else PartitionManagementInput()++ @temporalio.workflow.run+ async def run(self, inputs: PartitionManagementInput) -> dict:+ return await temporalio.workflow.execute_activity(+ manage_warehouse_sources_queue_partitions,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )