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-warehouse): bound the lock wait on queue partition ddl (#128903)

estefania7224411fcfb8
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.py
index e82a27c776c0..bffb6bca3dde 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
@@ -47,9 +47,12 @@ class _FakePgConn:
denied_creates: frozenset[str] = frozenset(),
denied_drops: frozenset[str] = frozenset(),
denied_deletes: frozenset[str] = frozenset(),
+ locked_tables: frozenset[str] = frozenset(),
) -> None:
self.partitions = partitions if partitions is not None else {}
self.default_rows = default_rows if default_rows is not None else {}
+ self.locked_tables = locked_tables
+ self.create_attempts: list[str] = []
self.denied_creates = denied_creates
self.denied_drops = denied_drops
self.denied_deletes = denied_deletes
@@ -73,6 +76,9 @@ class _FakePgConn:
elif sql.startswith("CREATE TABLE IF NOT EXISTS "):
tokens = sql.split()
partition_name, table = tokens[5], tokens[8]
+ self.create_attempts.append(partition_name)
+ if table in self.locked_tables:
+ raise psycopg.errors.LockNotAvailable("canceling statement due to lock timeout")
if partition_name in self.denied_creates:
raise psycopg.errors.InsufficientPrivilege(f"must be owner of table {table}")
if partition_name not in self.partitions.setdefault(table, []):
@@ -295,6 +301,28 @@ async def test_activity_runs_queue_database_statements_on_a_pool_thread(activity
assert conn.execute_threads.isdisjoint({threading.get_ident(), shared_thread_sensitive_ident})
+async def test_activity_skips_a_locked_table_and_finishes_the_rest_of_the_run(activity_environment) -> None:
+ conn = _FakePgConn(
+ {"sourcebatchstatus": [f"sourcebatchstatus_{_day(-9)}"]}, locked_tables=frozenset({"sourcebatch"})
+ )
+
+ with (
+ patch.object(activities_module.psycopg.Connection, "connect", return_value=conn),
+ patch.object(activities_module, "PARTITION_DDL_RETRY_DELAY_SECONDS", 0),
+ time_machine.travel(datetime.combine(ALERT_TODAY, datetime.min.time(), tzinfo=UTC), tick=False),
+ ):
+ result = await activity_environment.run(manage_warehouse_sources_queue_partitions)
+
+ first_sourcebatch = f"sourcebatch_{_day(0)}"
+ assert [p for p in conn.create_attempts if p.startswith("sourcebatch_")] == [
+ first_sourcebatch
+ ] * activities_module.PARTITION_DDL_ATTEMPTS
+ assert result["errors"] == [f"Failed to create {first_sourcebatch}: canceling statement due to lock timeout"]
+ assert sum(p.startswith("sourcebatchstatus_") for p in result["ensured"]) == activities_module.PARTITIONS_AHEAD
+ assert result["dropped"] == [f"sourcebatchstatus_{_day(-9)}"]
+
+
@pytest.mark.asyncio
async def test_activity_keeps_partition_when_terminalization_fails(activity_environment) -> None:
partitions = {
@@ -411,6 +439,42 @@ def test_expire_default_partition_rows_deletes_only_rows_older_than_cutoff_in_ba
assert remaining == [100, 101]
+def test_partition_ddl_gives_up_on_a_held_lock_and_resets_lock_timeout() -> None:
+ table = f"lock_test_{uuid4().hex[:12]}"
+ create_partition = (
+ f"CREATE TABLE IF NOT EXISTS {table}_20261002 PARTITION OF {table} "
+ "FOR VALUES FROM ('2026-10-02') TO ('2026-10-03')"
+ )
+
+ with (
+ psycopg.Connection.connect(_test_database_conninfo(), autocommit=True) as conn,
+ psycopg.Connection.connect(_test_database_conninfo()) as reader,
+ ):
+ try:
+ conn.execute(f"CREATE TABLE {table} (id int, created_at timestamptz) PARTITION BY RANGE (created_at)")
+ conn.execute("SET statement_timeout = '10s'")
+ reader.execute(f"SELECT * FROM {table}")
+
+ with (
+ patch.object(activities_module, "PARTITION_DDL_LOCK_TIMEOUT", "50ms"),
+ patch.object(activities_module, "PARTITION_DDL_RETRY_DELAY_SECONDS", 0),
+ pytest.raises(psycopg.errors.LockNotAvailable),
+ ):
+ activities_module._execute_partition_ddl(conn, create_partition)
+
+ row = conn.execute("SHOW lock_timeout").fetchone()
+ reader.rollback()
+ activities_module._execute_partition_ddl(conn, create_partition)
+ partitions = activities_module._list_partitions(conn, table)
+ finally:
+ reader.rollback()
+ conn.execute(f"DROP TABLE IF EXISTS {table}")
+
+ assert row == ("0",)
+ assert partitions == [f"{table}_20261002"]
+
+
def _connect_refused(*args: Any, **kwargs: Any) -> None:
del args, kwargs
raise psycopg.OperationalError("connection refused")
diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
index d19132c2380d..6ed767d2d427 100644
--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import time
from dataclasses import dataclass
from datetime import UTC, date, datetime, timedelta
from typing import Any
@@ -23,6 +24,14 @@ PARTITIONS_AHEAD = 7
RETENTION_DAYS = 7
DEFAULT_PARTITION_DELETE_BATCH_SIZE = 10_000
+# Creating or dropping a partition takes an ACCESS EXCLUSIVE lock on the parent table. While that
+# request waits behind any open reader, Postgres queues every later query on the table behind it,
+# so an unbounded wait stops the whole sync queue. Partitions exist PARTITIONS_AHEAD days ahead,
+# so giving up and leaving the work for the next run is safe.
+PARTITION_DDL_LOCK_TIMEOUT = "3s"
+PARTITION_DDL_ATTEMPTS = 3
+PARTITION_DDL_RETRY_DELAY_SECONDS = 2.0
+
# Rows in these tables change state in place two or three times, and each change leaves a dead
# entry in the partial indexes on latest_state. A scale factor waits for 10% of a partition to be
# dead, which late in the day is ~150k rows, and the claim query then reads through those entries.
@@ -68,9 +77,9 @@ async 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.
+ # Partition DDL waits on locks and sleeps between retries. Run the database work on the general
+ # thread pool so that the waits block 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)
result = PartitionResult(ensured=changes.ensured, dropped=changes.dropped, errors=errors)
@@ -106,12 +115,18 @@ def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionCha
d = today + timedelta(days=offset)
partition_name = f"{table}_{d.strftime('%Y%m%d')}"
try:
- conn.execute(
+ _execute_partition_ddl(
+ conn,
f"CREATE TABLE IF NOT EXISTS {partition_name} "
f"PARTITION OF {table} "
- f"FOR VALUES FROM ('{d.isoformat()}') TO ('{(d + timedelta(days=1)).isoformat()}')"
+ f"FOR VALUES FROM ('{d.isoformat()}') TO ('{(d + timedelta(days=1)).isoformat()}')",
)
ensured.append(partition_name)
+ except psycopg.errors.LockNotAvailable as e:
+ # The parent table stays locked, so the later days of this table would only wait again.
+ errors.append(f"Failed to create {partition_name}: {e}")
+ logger.exception("Failed to create partition", partition=partition_name)
+ break
except Exception as e:
errors.append(f"Failed to create {partition_name}: {e}")
logger.exception("Failed to create partition", partition=partition_name)
@@ -200,16 +215,31 @@ def _partition_date(partition_name: str) -> date | None:
return None
+def _execute_partition_ddl(conn: psycopg.Connection, statement: str) -> None:
+ conn.execute(f"SET lock_timeout = '{PARTITION_DDL_LOCK_TIMEOUT}'")
+ try:
+ for attempt in range(1, PARTITION_DDL_ATTEMPTS + 1):
+ try:
+ conn.execute(statement)
+ return
+ except psycopg.errors.LockNotAvailable:
+ if attempt == PARTITION_DDL_ATTEMPTS:
+ raise
+ time.sleep(PARTITION_DDL_RETRY_DELAY_SECONDS * attempt)
+ finally:
+ conn.execute("RESET lock_timeout")
+
+
def _drop_partition(conn: psycopg.Connection, partition_name: str) -> None:
try:
- conn.execute(f"DROP TABLE IF EXISTS {partition_name}")
+ _execute_partition_ddl(conn, 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}")
+ _execute_partition_ddl(owner_conn, f"DROP TABLE IF EXISTS {partition_name}")
def _expire_default_partition_rows(