: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 job as the table owner (#104750)
Daniel RC1c9a5ebc2df0
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex d78c4a229fd7..c9785fe2bfef 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -811,6 +811,7 @@ 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_DATABASE_URL: str = os.getenv("WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL", "")WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL: str = os.getenv("WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL", "")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 f45d5dbb46ed..8347c5ce853f 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@@ -3,14 +3,19 @@from __future__ import annotationsfrom contextlib import contextmanager-from datetime import date+from datetime import UTC, date, datetimefrom types import TracebackTypefrom typing import Any, Literal+from uuid import uuid4import pytest+import time_machinefrom unittest.mock import MagicMock, call, patch+from django.db import connection+import psycopg+from psycopg.conninfo import make_conninfofrom posthog.temporal.warehouse_sources_queue_partition_management import activities as activities_modulefrom posthog.temporal.warehouse_sources_queue_partition_management.activities import (@@ -309,9 +314,13 @@ class _FakePgConn:in ``dropped``."""- def __init__(self, partitions: dict[str, list[str]] | None = None) -> None:+ def __init__(+ self, partitions: dict[str, list[str]] | None = None, *, denied_drops: frozenset[str] = frozenset()+ ) -> None:self.partitions = partitions or {}+ self.denied_drops = denied_dropsself.dropped: list[str] = []+ self.deleted: list[tuple[str, datetime]] = []def __enter__(self) -> _FakePgConn:return self@@ -322,10 +331,16 @@ class _FakePgConn:def execute(self, sql: Any, params: Any = None) -> MagicMock:cursor = MagicMock()cursor.fetchall.return_value = []+ cursor.rowcount = 0if "pg_inherits" in sql and params:cursor.fetchall.return_value = [(name,) for name in self.partitions.get(params[0], [])]elif sql.startswith("DROP TABLE IF EXISTS "):- self.dropped.append(sql.removeprefix("DROP TABLE IF EXISTS "))+ partition_name = sql.removeprefix("DROP TABLE IF EXISTS ")+ if partition_name in self.denied_drops:+ raise psycopg.errors.InsufficientPrivilege(f"must be owner of table {partition_name}")+ self.dropped.append(partition_name)+ elif sql.strip().startswith("DELETE FROM "):+ self.deleted.append((sql.split()[2], params["created_before"]))return cursor@@ -357,13 +372,28 @@ async def test_activity_result_includes_s3_deleted(activity_environment) -> None@pytest.mark.asyncio-async def test_activity_s3_failure_marks_success_false_and_triggers_slack(activity_environment) -> None:+ ("ls_raises", "delete_raises", "expected_error"),+ [+ (+ None,+ {f"{BASE}/dt=2000-01-01": OSError("kaboom")},+ "Failed to delete S3 partition dt=2000-01-01: kaboom",+ ),+ (PermissionError("Access Denied"), None, "Failed to list S3 extraction partitions: Access Denied"),+ ],+)+async def test_activity_s3_failure_marks_success_false_and_triggers_slack(+ activity_environment,+ ls_raises: Exception | None,+ delete_raises: dict[str, Exception] | None,+ expected_error: str,+) -> None:entries = [f"{BASE}/dt=2000-01-01"]- delete_raises: dict[str, Exception] = {f"{BASE}/dt=2000-01-01": OSError("kaboom")}with (_patched_pg(),- _patched_s3(entries, delete_raises=delete_raises),+ _patched_s3(entries, ls_raises=ls_raises, delete_raises=delete_raises),patch.object(activities_module.settings, "WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL", "https://hooks/x"),@@ -373,7 +403,7 @@ async def test_activity_s3_failure_marks_success_false_and_triggers_slack(activiresult = await activity_environment.run(manage_warehouse_sources_queue_partitions)assert result["success"] is False- assert result["errors"] == ["Failed to delete S3 partition dt=2000-01-01: kaboom"]+ assert result["errors"] == [expected_error]assert result["s3_deleted"] == []post.assert_called_once()@@ -503,6 +533,100 @@ async def test_activity_keeps_partition_when_terminalization_fails(activity_enviassert any(OLD_BATCH_PART in e for e in result["errors"])+PARTITION_ROLE_URL = "postgres://[email protected]/queue"+WORKER_ROLE_URL = "postgres://[email protected]/queue"+++ ("partition_url", "expected_urls", "expect_dropped"),+ [+ (PARTITION_ROLE_URL, [PARTITION_ROLE_URL, WORKER_ROLE_URL], True),+ ("", [WORKER_ROLE_URL], False),+ ],+)+async def test_activity_uses_partition_role_and_drops_worker_owned_partitions_as_worker(+ activity_environment, partition_url: str, expected_urls: list[str], expect_dropped: bool+) -> None:+ ddl_conn = _FakePgConn({"sourcebatchstatus": [OLD_STATUS_PART]}, denied_drops=frozenset({OLD_STATUS_PART}))+ owner_conn = _FakePgConn()++ with (+ patch.object(activities_module.settings, "WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL", partition_url),+ patch.object(activities_module.settings, "WAREHOUSE_SOURCES_DATABASE_URL", WORKER_ROLE_URL),+ patch.object(activities_module.psycopg.Connection, "connect", side_effect=[ddl_conn, owner_conn]) as connect,+ patch.object(activities_module, "_verify_partitions"),+ _patched_s3([]),+ ):+ result = await activity_environment.run(manage_warehouse_sources_queue_partitions)++ assert [c.args[0] for c in connect.call_args_list] == expected_urls+ assert (OLD_STATUS_PART in result["dropped"]) is expect_dropped+ assert owner_conn.dropped == ([OLD_STATUS_PART] if expect_dropped else [])+ assert result["success"] is expect_dropped+++async def test_activity_expires_old_default_partition_rows_instead_of_dropping(activity_environment) -> None:+ partitions = {"sourcebatch": ["sourcebatch_default"], "sourcebatchstatus": ["sourcebatchstatus_default"]}+ cutoff = datetime(2026, 9, 15, tzinfo=UTC)++ with (+ time_machine.travel("2026-09-22T12:00:00Z", tick=False),+ _patched_pg(partitions) as conn,+ _patched_s3([]),+ patch.object(activities_module, "_terminalize_stranded_runs") as terminalize,+ ):+ result = await activity_environment.run(manage_warehouse_sources_queue_partitions)++ terminalize.assert_called_once_with(conn, "sourcebatch_default", created_before=cutoff)+ assert conn.deleted == [("sourcebatch_default", cutoff), ("sourcebatchstatus_default", cutoff)]+ assert conn.dropped == []+ assert result["success"] is True+++def _test_database_conninfo() -> str:+ settings_dict = connection.settings_dict+ params = {+ "host": settings_dict["HOST"],+ "port": str(settings_dict["PORT"] or ""),+ "user": settings_dict["USER"],+ "password": settings_dict["PASSWORD"],+ "dbname": settings_dict["NAME"],+ }+ return make_conninfo(**{key: value for key, value in params.items() if value})+++def test_expire_default_partition_rows_deletes_only_rows_older_than_cutoff_in_batches() -> None:+ table = f"expiry_test_{uuid4().hex[:12]}"+ cutoff = date(2026, 9, 15)+ errors: list[str] = []++ with psycopg.Connection.connect(_test_database_conninfo(), autocommit=True) as conn:+ try:+ conn.execute(f"CREATE TABLE {table} (id int, created_at timestamptz) PARTITION BY RANGE (created_at)")+ conn.execute(f"CREATE TABLE {table}_default PARTITION OF {table} DEFAULT")+ conn.execute(+ f"""+ INSERT INTO {table}+ SELECT g, timestamptz '2026-09-14 23:59:59+00' - g * interval '1 hour' FROM generate_series(1, 5) g+ UNION ALL+ SELECT 100 + g, timestamptz '2026-09-15 00:00:00+00' + g * interval '1 hour' FROM generate_series(0, 1) g+ """+ )++ with patch.object(activities_module, "DEFAULT_PARTITION_DELETE_BATCH_SIZE", 2):+ activities_module._expire_default_partition_rows(conn, table, f"{table}_default", cutoff, errors)++ remaining = [row[0] for row in conn.execute(f"SELECT id FROM {table} ORDER BY id").fetchall()]+ finally:+ conn.execute(f"DROP TABLE IF EXISTS {table}")++ assert errors == []+ assert remaining == [100, 101]++@pytest.mark.asyncioasync def test_activity_logs_s3_deleted_count(activity_environment) -> None:entries = [diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex 10b63a9abe2a..fbc46b9dc962 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -17,6 +17,7 @@ logger = structlog.get_logger(__name__)PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus"]PARTITIONS_AHEAD = 7RETENTION_DAYS = 7+DEFAULT_PARTITION_DELETE_BATCH_SIZE = 10_000# Deliberately not the lock-takeover sentinel — that string has special# downstream semantics in the dead-job gate.@@ -45,7 +46,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:dropped: list[str] = []errors: list[str] = []- with psycopg.Connection.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ with psycopg.Connection.connect(_partition_ddl_database_url(), autocommit=True) as conn:today = datetime.now(UTC).date()for table in PARTITIONED_TABLES:@@ -76,6 +77,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)continuesuffix = partition_name.rsplit("_", 1)[-1]try:@@ -96,7 +98,7 @@ async def manage_warehouse_sources_queue_partitions() -> dict:)continuetry:- conn.execute(f"DROP TABLE IF EXISTS {partition_name}")+ await sync_to_async(_drop_partition)(conn, partition_name)dropped.append(partition_name)except Exception as e:errors.append(f"Failed to drop {partition_name}: {e}")@@ -129,7 +131,63 @@ async def manage_warehouse_sources_queue_partitions() -> dict:}-def _terminalize_stranded_runs(conn: psycopg.Connection, partition_name: str) -> None:+def _partition_ddl_database_url() -> str:+ # Only the owner of a partitioned table can create its partitions, and the migration role owns the queue tables.+ return settings.WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL or settings.WAREHOUSE_SOURCES_DATABASE_URL+++def _drop_partition(conn: psycopg.Connection, partition_name: str) -> None:+ try:+ conn.execute(f"DROP TABLE IF EXISTS {partition_name}")+ except psycopg.errors.InsufficientPrivilege:+ # Only a table's owner can drop it. Partitions created before this job used the+ # migration role are owned by the worker's own role, so drop those with that role.+ if not settings.WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL:+ raise+ with psycopg.Connection.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as owner_conn:+ owner_conn.execute(f"DROP TABLE IF EXISTS {partition_name}")+++def _expire_default_partition_rows(+ conn: psycopg.Connection, table: str, partition_name: str, cutoff: date, errors: list[str]+) -> None:+ """Apply retention to rows in the default partition.++ Rows land in the default partition only for days that had no daily partition. Retention+ removes data by dropping daily partitions, so without this step those rows stay forever.+ """+ created_before = datetime.combine(cutoff, datetime.min.time(), tzinfo=UTC)+ try:+ if table == "sourcebatch":+ _terminalize_stranded_runs(conn, partition_name, created_before=created_before)+ deleted = 0+ while True:+ # Bounded batches keep each statement short after an outage leaves several days of rows.+ batch_deleted = conn.execute(+ f"""+ DELETE FROM {partition_name}+ WHERE ctid = ANY(ARRAY(+ SELECT ctid FROM {partition_name}+ WHERE created_at < %(created_before)s+ LIMIT %(limit)s+ ))+ """,+ {"created_before": created_before, "limit": DEFAULT_PARTITION_DELETE_BATCH_SIZE},+ ).rowcount+ deleted += batch_deleted+ if batch_deleted < DEFAULT_PARTITION_DELETE_BATCH_SIZE:+ break+ except Exception as e:+ errors.append(f"Failed to expire old rows in {partition_name}: {e}")+ logger.exception("Failed to expire old default partition rows", partition=partition_name)+ return+ if deleted:+ logger.warning("Expired old default partition rows", partition=partition_name, deleted=deleted)+++def _terminalize_stranded_runs(+ conn: psycopg.Connection, partition_name: str, *, created_before: datetime | None = None+) -> None:"""Fail runs that still have non-terminal batches in ``partition_name`` before it is dropped.Dropping the data itself is deliberate — the staged cursor never promoted,@@ -152,6 +210,7 @@ def _terminalize_stranded_runs(conn: psycopg.Connection, partition_name: str) ->)states = ", ".join(f"'{s}'" for s in _NON_TERMINAL_BATCH_STATES)+ created_filter = "AND created_at < %(created_before)s" if created_before else ""stranded = conn.execute(f"""SELECT run_uuid, team_id, schema_id, job_id,@@ -159,9 +218,11 @@ def _terminalize_stranded_runs(conn: psycopg.Connection, partition_name: str) ->COUNT(*) AS non_terminal_batchesFROM {partition_name}WHERE latest_state IN ({states})+ {created_filter}GROUP BY run_uuid, team_id, schema_id, job_idORDER BY run_uuid- """+ """,+ {"created_before": created_before} if created_before else None,).fetchall()if not stranded:return@@ -220,6 +281,11 @@ def _cleanup_old_s3_extractions(today: date, errors: list[str]) -> list[str]:except FileNotFoundError:logger.debug("s3_extraction_prefix_not_found", prefix=base_prefix)return deleted+ except Exception as e:+ # Record instead of raising, because a raise here skips the Slack alert for every error so far.+ errors.append(f"Failed to list S3 extraction partitions: {e}")+ logger.exception("Failed to list S3 extraction partitions", prefix=base_prefix)+ return deletedfor entry in entries:name = entry.rstrip("/").rsplit("/", 1)[-1]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.mdindex 76826d60ed42..15a61886d5a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md@@ -51,8 +51,11 @@ All SQL lives in `jobs_db.py`; the polling/retry/recovery engine is `../batch_co- **Sync producer** (`producer.py`): runs inside Temporal activities, plain `psycopg.Connection` with autocommit. Each `send_batch_notification` is a single INSERT.- **New DB**: we created a new DB to store these tables.- **Daily range partitioning** on `created_at`: both tables use `PARTITION BY RANGE (created_at)` with daily partitions and a DEFAULT partition catching rows that miss one.- A Temporal scheduled workflow (`warehouse-sources-queue-partition-management`, daily at 8 AM UTC) creates the next 7 days of partitions, drops partitions older than 7 days, and prunes the matching S3 extraction prefixes on the same retention.+ A Temporal scheduled workflow (`warehouse-sources-queue-partition-management`, daily at 8 AM UTC) creates the next 7 days of partitions, drops partitions older than 7 days, deletes DEFAULT-partition rows older than 7 days, and prunes the matching S3 extraction prefixes on the same retention.`DROP TABLE partition` is O(1) metadata-only: no vacuum, no dead tuples.+ The workflow connects with `WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL`, the migration role's credentials, because Postgres lets only the owner of a partitioned table create partitions of it.+ The worker's own queue role cannot create partitions, because it does not own the parent tables.+ Partitions that the worker role created earlier still belong to it, so the workflow drops those with that role.- **Claim eligibility coupled to retention**: a batch is only claimable (or recovery-sweepable) while younger than `CLAIM_ELIGIBILITY_INTERVAL` (`6 days 12 hours`, `jobs_db.py`), which must stay below the 7-day retention window (`RETENTION_DAYS` in `posthog/temporal/warehouse_sources_queue_partition_management/activities.py`).Otherwise a claimed batch's extraction parquet may already be deleted from S3 when the loader reads it.`test_eligibility_window_stays_below_retention_window` in `test_jobs_db.py` enforces the coupling.