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): move extract cleanup to s3, alert only when needed (#109182)

Daniel RCd274095196be
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 74699ea6f853..a643937d96d8 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
@@ -4,7 +4,7 @@ from __future__ import annotations
import threading
from contextlib import contextmanager
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from types import TracebackType
from typing import Any, Literal
from uuid import uuid4
@@ -22,289 +22,10 @@ from psycopg.conninfo import make_conninfo
from posthog.temporal.warehouse_sources_queue_partition_management import activities as activities_module
from posthog.temporal.warehouse_sources_queue_partition_management.activities import (
RETENTION_STRANDED_ERROR,
- _cleanup_old_s3_extractions,
_terminalize_stranded_runs,
manage_warehouse_sources_queue_partitions,
)
-TODAY = date(2026, 5, 22)
-BUCKET = "data-warehouse"
-BASE = f"{BUCKET}/data_pipelines_extract"
-
-
-def _build_s3_mock(
- entries: list[str],
- *,
- ls_raises: Exception | None = None,
- delete_raises: dict[str, Exception] | None = None,
-) -> MagicMock:
- s3 = MagicMock()
- if ls_raises is not None:
- s3.ls.side_effect = ls_raises
- else:
- s3.ls.return_value = entries
-
- if delete_raises:
-
- def _delete(path: str, recursive: bool) -> None:
- if path in delete_raises:
- raise delete_raises[path]
-
- s3.delete.side_effect = _delete
- return s3
-
-
-@contextmanager
-def _patched_s3(
- entries: list[str],
- *,
- ls_raises: Exception | None = None,
- delete_raises: dict[str, Exception] | None = None,
- bucket: str = BUCKET,
-):
- s3 = _build_s3_mock(entries, ls_raises=ls_raises, delete_raises=delete_raises)
- with (
- patch("products.data_warehouse.backend.s3.get_s3_client", return_value=s3),
- patch.object(activities_module.settings, "DATAWAREHOUSE_BUCKET", bucket),
- ):
- yield s3
-
-
-# Cutoff arithmetic
-
-
- ("partition_date", "should_delete", "note"),
- [
- (date(2026, 5, 15), False, "exactly at cutoff -> keep (guards against `<=` flip)"),
- (date(2026, 5, 14), True, "one day before cutoff -> delete"),
- (date(2026, 5, 16), False, "one day after cutoff -> keep"),
- (date(2026, 5, 22), False, "today -> keep"),
- (date(2026, 6, 1), False, "future-dated -> keep (defense against clock skew)"),
- (date(2020, 1, 1), True, "far old -> delete"),
- ],
-)
-def test_cutoff_boundaries(partition_date: date, should_delete: bool, note: str) -> None:
- name = f"dt={partition_date.isoformat()}"
- entries = [f"{BASE}/{name}"]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert errors == []
- if should_delete:
- assert deleted == [name]
- s3.delete.assert_called_once_with(entries[0], recursive=True)
- else:
- assert deleted == []
- s3.delete.assert_not_called()
-
-
-# Name parsing / filtering safety
-
-
-def test_skips_entries_without_dt_prefix() -> None:
- entries = [
- f"{BASE}/README.md",
- f"{BASE}/_temp",
- f"{BASE}/year=2024",
- f"{BASE}/dt=2020-01-01",
- ]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == ["dt=2020-01-01"]
- assert errors == []
- s3.delete.assert_called_once_with(f"{BASE}/dt=2020-01-01", recursive=True)
-
-
- "bad_entry",
- [
- "dt=invalid",
- "dt=2026-13-40",
- "dt=",
- "dt=2026/05/15",
- "dt=2020-01-01-extra",
- ],
-)
-def test_skips_dt_entries_with_unparseable_date(bad_entry: str) -> None:
- entries = [f"{BASE}/{bad_entry}"]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == []
- s3.delete.assert_not_called()
-
-
-def test_handles_entries_with_and_without_trailing_slash() -> None:
- entries = [
- f"{BASE}/dt=2020-01-01/",
- f"{BASE}/dt=2020-02-02",
- ]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert set(deleted) == {"dt=2020-01-01", "dt=2020-02-02"}
- assert errors == []
- assert s3.delete.call_count == 2
- s3.delete.assert_any_call(f"{BASE}/dt=2020-01-01/", recursive=True)
- s3.delete.assert_any_call(f"{BASE}/dt=2020-02-02", recursive=True)
-
-
-def test_uses_basename_for_date_parsing_not_full_path() -> None:
- entries = ["s3://other-bucket/data_pipelines_extract/dt=2020-01-01/"]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == ["dt=2020-01-01"]
- assert errors == []
- s3.delete.assert_called_once_with(entries[0], recursive=True)
-
-
-# S3 listing edges
-
-
-def test_returns_empty_when_prefix_does_not_exist() -> None:
- errors: list[str] = []
-
- with _patched_s3([], ls_raises=FileNotFoundError()) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == []
- s3.delete.assert_not_called()
-
-
-def test_returns_empty_when_prefix_has_no_entries() -> None:
- errors: list[str] = []
-
- with _patched_s3([]) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == []
- s3.delete.assert_not_called()
-
-
-def test_returns_empty_when_no_entries_old_enough() -> None:
- entries = [
- f"{BASE}/dt=2026-05-20",
- f"{BASE}/dt=2026-05-21",
- f"{BASE}/dt=2026-05-22",
- ]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == []
- s3.delete.assert_not_called()
-
-
-# Per-entry failure isolation
-
-
-def test_continues_after_individual_delete_failure() -> None:
- entries = [
- f"{BASE}/dt=2020-01-01",
- f"{BASE}/dt=2020-01-02",
- f"{BASE}/dt=2020-01-03",
- ]
- errors: list[str] = []
-
- with _patched_s3(entries, delete_raises={f"{BASE}/dt=2020-01-02": OSError("boom")}) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert set(deleted) == {"dt=2020-01-01", "dt=2020-01-03"}
- assert errors == ["Failed to delete S3 partition dt=2020-01-02: boom"]
- assert s3.delete.call_count == 3
-
-
-def test_appends_error_for_each_failed_delete() -> None:
- entries = [
- f"{BASE}/dt=2020-01-01",
- f"{BASE}/dt=2020-01-02",
- ]
- errors: list[str] = []
- delete_raises: dict[str, Exception] = {
- f"{BASE}/dt=2020-01-01": OSError("first"),
- f"{BASE}/dt=2020-01-02": OSError("second"),
- }
-
- with _patched_s3(entries, delete_raises=delete_raises):
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == [
- "Failed to delete S3 partition dt=2020-01-01: first",
- "Failed to delete S3 partition dt=2020-01-02: second",
- ]
-
-
-def test_failure_does_not_mark_unrelated_skipped_entries() -> None:
- entries = [
- f"{BASE}/dt=2020-01-01",
- f"{BASE}/dt=2026-05-22",
- f"{BASE}/not-a-partition",
- f"{BASE}/dt=invalid",
- ]
- errors: list[str] = []
-
- with _patched_s3(entries, delete_raises={f"{BASE}/dt=2020-01-01": OSError("x")}) as s3:
- deleted = _cleanup_old_s3_extractions(TODAY, errors)
-
- assert deleted == []
- assert errors == ["Failed to delete S3 partition dt=2020-01-01: x"]
- s3.delete.assert_called_once_with(f"{BASE}/dt=2020-01-01", recursive=True)
-
-
-# Call shape
-
-
-def test_calls_delete_with_recursive_true() -> None:
- entries = [f"{BASE}/dt=2020-01-01"]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- _cleanup_old_s3_extractions(TODAY, errors)
-
- # without recursive=True we'd leak every parquet file under the prefix
- _, kwargs = s3.delete.call_args
- assert kwargs == {"recursive": True}
-
-
-def test_uses_full_entry_path_when_deleting() -> None:
- full_path = "s3://some-bucket/data_pipelines_extract/dt=2020-01-01"
- entries = [full_path]
- errors: list[str] = []
-
- with _patched_s3(entries) as s3:
- _cleanup_old_s3_extractions(TODAY, errors)
-
- s3.delete.assert_called_once_with(full_path, recursive=True)
-
-
-def test_uses_configured_bucket_prefix() -> None:
- errors: list[str] = []
-
- with _patched_s3([], bucket="my-special-bucket") as s3:
- _cleanup_old_s3_extractions(TODAY, errors)
-
- s3.ls.assert_called_once_with("my-special-bucket/data_pipelines_extract")
-
-
# Activity-level integration
@@ -312,15 +33,26 @@ class _FakePgConn:
"""Minimal psycopg.Connection stand-in: context manager + .execute returning a cursor.
``partitions`` (parent table -> partition names) feeds the pg_inherits
- listing so the drop loop has something to drop; executed DROPs are recorded
- in ``dropped``.
+ listing. Executed CREATEs add to it and executed DROPs remove from it, so
+ the listing after the run reflects what the activity did. DROPs are also
+ recorded in ``dropped``. ``default_rows`` (default partition -> row
+ ``created_at`` values) works the same way for DELETEs.
"""
def __init__(
- self, partitions: dict[str, list[str]] | None = None, *, denied_drops: frozenset[str] = frozenset()
+ self,
+ partitions: dict[str, list[str]] | None = None,
+ *,
+ default_rows: dict[str, list[datetime]] | None = None,
+ denied_creates: frozenset[str] = frozenset(),
+ denied_drops: frozenset[str] = frozenset(),
+ denied_deletes: frozenset[str] = frozenset(),
) -> None:
- self.partitions = partitions or {}
+ self.partitions = partitions if partitions is not None else {}
+ self.default_rows = default_rows if default_rows is not None else {}
+ self.denied_creates = denied_creates
self.denied_drops = denied_drops
+ self.denied_deletes = denied_deletes
self.dropped: list[str] = []
self.deleted: list[tuple[str, datetime]] = []
self.execute_threads: set[int] = set()
@@ -338,78 +70,117 @@ class _FakePgConn:
cursor.rowcount = 0
if "pg_inherits" in sql and params:
cursor.fetchall.return_value = [(name,) for name in self.partitions.get(params[0], [])]
+ elif sql.startswith("CREATE TABLE IF NOT EXISTS "):
+ tokens = sql.split()
+ partition_name, table = tokens[5], tokens[8]
+ 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, []):
+ self.partitions[table].append(partition_name)
elif sql.startswith("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)
+ for names in self.partitions.values():
+ if partition_name in names:
+ names.remove(partition_name)
elif sql.strip().startswith("DELETE FROM "):
- self.deleted.append((sql.split()[2], params["created_before"]))
+ partition_name, created_before = sql.split()[2], params["created_before"]
+ if partition_name in self.denied_deletes:
+ raise psycopg.errors.InsufficientPrivilege(f"permission denied for table {partition_name}")
+ self.deleted.append((partition_name, created_before))
+ rows = self.default_rows.get(partition_name, [])
+ self.default_rows[partition_name] = [r for r in rows if r >= created_before]
+ cursor.rowcount = len(rows) - len(self.default_rows[partition_name])
+ elif sql.startswith("SELECT EXISTS "):
+ partition_name = sql.split()[5]
+ cursor.fetchone.return_value = (any(r < params[0] for r in self.default_rows.get(partition_name, [])),)
return cursor
@contextmanager
def _patched_pg(partitions: dict[str, list[str]] | None = None):
- # _verify_partitions is stubbed because the fake connection returns no rows, which would
- # otherwise flood `errors` with bogus "partition missing" messages — orthogonal to the
- # S3-cleanup wiring these integration tests cover.
conn = _FakePgConn(partitions)
- with (
- patch.object(activities_module.psycopg.Connection, "connect", return_value=conn),
- patch.object(activities_module, "_verify_partitions"),
- ):
+ with patch.object(activities_module.psycopg.Connection, "connect", return_value=conn):
yield conn
-async def test_activity_result_includes_s3_deleted(activity_environment) -> None:
- # Use a date guaranteed to be older than 7 days from real `date.today()` so we don't have
- # to patch the date module — the cutoff math itself is exhaustively tested above.
- entries = [f"{BASE}/dt=2000-01-01"]
+ALERT_TODAY = date(2026, 9, 22)
- with _patched_pg(), _patched_s3(entries):
- result = await activity_environment.run(manage_warehouse_sources_queue_partitions)
- assert result["s3_deleted"] == ["dt=2000-01-01"]
- assert result["errors"] == []
- assert result["success"] is True
+def _day(offset: int) -> str:
+ return (ALERT_TODAY + timedelta(days=offset)).strftime("%Y%m%d")
@pytest.mark.asyncio
@pytest.mark.parametrize(
- ("ls_raises", "delete_raises", "expected_error"),
+ ("partitions", "default_rows", "denied_creates", "denied_retention", "expected_alert"),
[
+ ({}, {}, {f"sourcebatch_{_day(1)}"}, set(), "`sourcebatch`: 2026-09-23"),
+ ({}, {}, {f"sourcebatch_{_day(0)}"}, set(), None),
+ ({}, {}, {f"sourcebatch_{_day(6)}"}, set(), None),
+ ({"sourcebatch": [f"sourcebatch_{_day(-9)}"]}, {}, set(), {f"sourcebatch_{_day(-9)}"}, "oldest 2026-09-13"),
+ ({"sourcebatch": [f"sourcebatch_{_day(-8)}"]}, {}, set(), {f"sourcebatch_{_day(-8)}"}, None),
(
+ {"sourcebatch": ["sourcebatch_default"]},
+ {"sourcebatch_default": [datetime(2026, 9, 13, 12, tzinfo=UTC)]},
+ set(),
+ {"sourcebatch_default"},
+ "`sourcebatch_default`: rows created before 2026-09-14",
+ ),
+ (
+ {"sourcebatch": ["sourcebatch_default"]},
+ {"sourcebatch_default": [datetime(2026, 9, 14, 12, tzinfo=UTC)]},
+ set(),
+ {"sourcebatch_default"},
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"),
+ ],
+ ids=[
+ "tomorrow_missing",
+ "only_today_missing",
+ "newest_partition_first_failure",
+ "drop_overdue_a_day",
+ "first_drop_failure",
+ "default_rows_overdue_a_day",
+ "first_default_expiry_failure",
],
)
-async def test_activity_s3_failure_marks_success_false_and_triggers_slack(
+async def test_activity_posts_to_slack_only_when_someone_must_act(
activity_environment,
- ls_raises: Exception | None,
- delete_raises: dict[str, Exception] | None,
- expected_error: str,
+ partitions: dict[str, list[str]],
+ default_rows: dict[str, list[datetime]],
+ denied_creates: set[str],
+ denied_retention: set[str],
+ expected_alert: str | None,
) -> None:
- entries = [f"{BASE}/dt=2000-01-01"]
+ conn = _FakePgConn(
+ {table: list(names) for table, names in partitions.items()},
+ default_rows={name: list(rows) for name, rows in default_rows.items()},
+ denied_creates=frozenset(denied_creates),
+ denied_drops=frozenset(denied_retention),
+ denied_deletes=frozenset(denied_retention),
+ )
with (
- _patched_pg(),
- _patched_s3(entries, ls_raises=ls_raises, delete_raises=delete_raises),
+ time_machine.travel("2026-09-22T08:00:00Z", tick=False),
+ patch.object(activities_module.psycopg.Connection, "connect", return_value=conn),
+ patch.object(activities_module.settings, "WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL", ""),
patch.object(
activities_module.settings, "WAREHOUSE_SOURCES_QUEUE_PARTITION_SLACK_WEBHOOK_URL", "https://hooks/x"
),
patch.object(activities_module.requests, "post") as post,
+ patch.object(activities_module, "_terminalize_stranded_runs"),
):
- post.return_value.raise_for_status = MagicMock()
result = await activity_environment.run(manage_warehouse_sources_queue_partitions)
assert result["success"] is False
- assert result["errors"] == [expected_error]
- assert result["s3_deleted"] == []
- post.assert_called_once()
+ if expected_alert is None:
+ post.assert_not_called()
+ else:
+ post.assert_called_once()
+ assert expected_alert in str(post.call_args.kwargs["json"])
# Terminalizing stranded runs before partition drops
@@ -499,7 +270,6 @@ async def test_activity_terminalizes_only_sourcebatch_partitions_then_drops(acti
with (
_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)
@@ -517,7 +287,6 @@ async def test_activity_runs_queue_database_statements_on_a_pool_thread(activity
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)
@@ -539,7 +308,6 @@ async def test_activity_keeps_partition_when_terminalization_fails(activity_envi
with (
_patched_pg(partitions) as conn,
- _patched_s3([]),
patch.object(activities_module, "_terminalize_stranded_runs", side_effect=_boom),
):
result = await activity_environment.run(manage_warehouse_sources_queue_partitions)
@@ -568,14 +336,12 @@ async def test_activity_uses_partition_role_and_drops_worker_owned_partitions_as
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()
+ owner_conn = _FakePgConn(ddl_conn.partitions)
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)
@@ -593,7 +359,6 @@ async def test_activity_expires_old_default_partition_rows_instead_of_dropping(a
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)
@@ -646,27 +411,6 @@ def test_expire_default_partition_rows_deletes_only_rows_older_than_cutoff_in_ba
assert remaining == [100, 101]
-async def test_activity_logs_s3_deleted_count(activity_environment) -> None:
- entries = [
- f"{BASE}/dt=2000-01-01",
- f"{BASE}/dt=2000-01-02",
- ]
-
- with (
- _patched_pg(),
- _patched_s3(entries),
- patch.object(activities_module.logger, "info") as log_info,
- ):
- await activity_environment.run(manage_warehouse_sources_queue_partitions)
-
- completion_calls = [
- call for call in log_info.call_args_list if call.args and call.args[0] == "Partition management completed"
- ]
- assert len(completion_calls) == 1
- assert completion_calls[0].kwargs["s3_deleted_count"] == 2
-
-
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 c91276aef45c..191487d35d69 100644
--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from datetime import UTC, date, datetime, timedelta
from typing import Any
@@ -10,9 +10,11 @@ import psycopg
import requests
import structlog
import temporalio.activity
+from asgiref.sync import sync_to_async
from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.warehouse_sources_queue_partition_management.schedule import SCHEDULE_ID
logger = structlog.get_logger(__name__)
@@ -35,7 +37,6 @@ class PartitionResult:
ensured: list[str]
dropped: list[str]
errors: list[str]
- s3_deleted: list[str] = field(default_factory=list)
@property
def success(self) -> bool:
@@ -46,6 +47,7 @@ class PartitionResult:
class _PartitionChanges:
ensured: list[str]
dropped: list[str]
+ alerts: list[str]
@temporalio.activity.defn
@@ -58,27 +60,25 @@ async def manage_warehouse_sources_queue_partitions() -> dict:
# 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)
+ result = PartitionResult(ensured=changes.ensured, dropped=changes.dropped, errors=errors)
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,
+ alerts=changes.alerts,
)
- if not result.success:
- _send_slack_failure(errors)
+ if changes.alerts:
+ await sync_to_async(_send_slack_alert, thread_sensitive=False)(changes.alerts)
return {
"ensured": result.ensured,
"dropped": result.dropped,
- "s3_deleted": result.s3_deleted,
"errors": result.errors,
+ "alerts": changes.alerts,
"success": result.success,
}
@@ -104,32 +104,23 @@ def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionCha
logger.exception("Failed to create partition", partition=partition_name)
cutoff = today - timedelta(days=RETENTION_DAYS)
+ failed_default_expiries: set[str] = set()
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]
+ for partition_name in _list_partitions(conn, table):
if partition_name.endswith("_default"):
- _expire_default_partition_rows(conn, table, partition_name, cutoff, errors)
+ if not _expire_default_partition_rows(conn, table, partition_name, cutoff, errors):
+ failed_default_expiries.add(partition_name)
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):
+ partition_date = _partition_date(partition_name)
+ if partition_date is None:
continue
if partition_date < cutoff:
if table == "sourcebatch":
try:
_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.
+ # Keep the partition as evidence. Partitions are daily and small,
+ # so retrying tomorrow is cheap.
errors.append(f"Failed to terminalize stranded runs in {partition_name}: {e}")
logger.exception(
"Failed to terminalize stranded runs before partition drop",
@@ -143,9 +134,9 @@ def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionCha
errors.append(f"Failed to drop {partition_name}: {e}")
logger.exception("Failed to drop partition", partition=partition_name)
- _verify_partitions(conn, today, errors)
+ alerts = _find_partition_alerts(conn, today, failed_default_expiries)
- return _PartitionChanges(ensured=ensured, dropped=dropped)
+ return _PartitionChanges(ensured=ensured, dropped=dropped, alerts=alerts)
def _partition_ddl_database_url() -> str:
@@ -153,6 +144,29 @@ def _partition_ddl_database_url() -> str:
return settings.WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL or settings.WAREHOUSE_SOURCES_DATABASE_URL
+def _list_partitions(conn: psycopg.Connection, table: str) -> list[str]:
+ return [
+ row[0]
+ 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()
+ ]
+
+
+def _partition_date(partition_name: str) -> date | None:
+ suffix = partition_name.rsplit("_", 1)[-1]
+ try:
+ return date(int(suffix[:4]), int(suffix[4:6]), int(suffix[6:8]))
+ except (ValueError, IndexError):
+ return None
+
+
def _drop_partition(conn: psycopg.Connection, partition_name: str) -> None:
try:
conn.execute(f"DROP TABLE IF EXISTS {partition_name}")
@@ -167,8 +181,8 @@ def _drop_partition(conn: psycopg.Connection, partition_name: str) -> None:
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.
+) -> bool:
+ """Apply retention to rows in the default partition, and return whether it finished.
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.
@@ -197,9 +211,10 @@ def _expire_default_partition_rows(
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
+ return False
if deleted:
logger.warning("Expired old default partition rows", partition=partition_name, deleted=deleted)
+ return True
def _terminalize_stranded_runs(
@@ -284,88 +299,78 @@ def _terminalize_stranded_runs(
)
-def _cleanup_old_s3_extractions(today: date, errors: list[str]) -> list[str]:
- """Delete S3 date-partitioned extraction prefixes older than RETENTION_DAYS."""
- from products.data_warehouse.backend.facade.api import get_s3_client
-
- s3 = get_s3_client()
- base_prefix = f"{settings.DATAWAREHOUSE_BUCKET}/data_pipelines_extract"
- cutoff = today - timedelta(days=RETENTION_DAYS)
- deleted: list[str] = []
+def _find_partition_alerts(conn: psycopg.Connection, today: date, failed_default_expiries: set[str]) -> list[str]:
+ """Return one Slack message for each problem that needs someone to act.
- try:
- entries = s3.ls(base_prefix)
- 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 deleted
-
- for entry in entries:
- name = entry.rstrip("/").rsplit("/", 1)[-1]
- if not name.startswith("dt="):
- continue
- try:
- partition_date = date.fromisoformat(name[3:])
- except ValueError:
- continue
- if partition_date < cutoff:
- try:
- s3.delete(entry, recursive=True)
- deleted.append(name)
- logger.debug("s3_extraction_partition_deleted", partition=name)
- except Exception as e:
- errors.append(f"Failed to delete S3 partition {name}: {e}")
- logger.exception("Failed to delete S3 extraction partition", partition=name)
-
- return deleted
-
-
-def _verify_partitions(conn: psycopg.Connection, today: date, errors: list[str]) -> None:
+ A missing partition for today does not alert. After rows for today land in the default
+ partition, Postgres refuses to create today's partition, and retention deletes those rows
+ later. A cause that also blocks tomorrow's partition still alerts through the upcoming check.
+ """
+ # The newest partition is the only one a run creates for the first time. Leaving it out gives a
+ # failed create one retry before it alerts, like the retention check below.
+ upcoming = [today + timedelta(days=offset) for offset in range(1, PARTITIONS_AHEAD - 1)]
+ # Data this old was due for removal in at least two daily runs, so one transient failure does not alert.
+ stuck_before = today - timedelta(days=RETENTION_DAYS + 1)
+ stuck_before_at = datetime.combine(stuck_before, datetime.min.time(), tzinfo=UTC)
+ missing: dict[str, list[date]] = {}
+ stuck: list[str] = []
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")
+ existing: set[date] = set()
+ for partition_name in _list_partitions(conn, table):
+ if partition_name.endswith("_default"):
+ # A finished expiry leaves no row this old, so scan the partition only when this run's expiry
+ # failed. The scan has no created_at index to use, and a default partition can hold days of rows.
+ if partition_name in failed_default_expiries:
+ row = conn.execute(
+ f"SELECT EXISTS (SELECT 1 FROM {partition_name} WHERE created_at < %s)", [stuck_before_at]
+ ).fetchone()
+ if row and row[0]:
+ stuck.append(f"• `{partition_name}`: rows created before {stuck_before.isoformat()}")
+ continue
+ partition_date = _partition_date(partition_name)
+ if partition_date is not None:
+ existing.add(partition_date)
+ if table_missing := [d for d in upcoming if d not in existing]:
+ missing[table] = table_missing
+ if table_stuck := sorted(d for d in existing if d < stuck_before):
+ stuck.append(f"• `{table}`: oldest {table_stuck[0].isoformat()} ({len(table_stuck)} in total)")
+
+ alerts: list[str] = []
+ if missing:
+ first_missing = min(dates[0] for dates in missing.values())
+ lines = "\n".join(f"• `{table}`: {', '.join(d.isoformat() for d in dates)}" for table, dates in missing.items())
+ alerts.append(
+ f"*Upcoming partitions are missing.* From {first_missing.isoformat()} 00:00 UTC, new rows land in "
+ f"the default partition. Once that happens, Postgres can't create the partition for that day.\n{lines}\n"
+ "Find the cause in the worker logs under `Failed to create partition`. Check that "
+ "`WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL` logs in as the role that owns the queue tables, "
+ f"then trigger the `{SCHEDULE_ID}` schedule."
+ )
+ if stuck:
+ lines = "\n".join(stuck)
+ alerts.append(
+ f"*Retention is stuck.* This data should have been removed at least a day ago:\n{lines}\n"
+ "Find the cause in the worker logs under `Failed to drop partition`, "
+ "`Failed to terminalize stranded runs`, or `Failed to expire old default partition rows`."
+ )
+ return alerts
-def _send_slack_failure(errors: list[str]) -> None:
+def _send_slack_alert(alerts: 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}```",
+ "text": ":rotating_light: *Warehouse sources queue partitions need attention*",
},
},
+ *({"type": "section", "text": {"type": "mrkdwn", "text": alert}} for alert in alerts),
]
try:
diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.md
index 0da8dd4e9295..8c79c383fe7d 100644
--- a/products/warehouse_sources_queue/backend/README.md
+++ b/products/warehouse_sources_queue/backend/README.md
@@ -54,14 +54,18 @@ All SQL lives in `core/jobs_db.py`; the polling/retry/recovery engine is `core/b
The CDC extraction activities know at send time whether a batch is final and keep using `send_batch_notification` directly.
- **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, deletes DEFAULT-partition rows 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, and deletes DEFAULT-partition rows older than 7 days.
+ It posts to Slack only when someone must act: a partition for one of the next 5 days is missing, or data is more than a day past retention, in a daily partition or in a DEFAULT partition.
+ An S3 lifecycle rule on the warehouse bucket expires the extraction files under `data_pipelines_extract/` after 8 days, so this workflow does not touch S3.
`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 `tests/test_jobs_db.py` enforces the coupling.
+ Otherwise the partition drop may delete a batch the loader has claimed.
+ The bucket's 8-day lifecycle rule for extraction files also stays above this window, so a claimable batch's parquet still exists.
+ `TestClaimEligibilityWindow` in `products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py` enforces the retention coupling.
+ The bucket rule lives in the infrastructure repo, and nothing in this repo checks it.
- **Partition pruning bounds**: consumer queries include `created_at > now() - interval '14 days'` (2x the retention) so the planner can skip dropped partitions.
### Query cost scales with the answer, not with history
@@ -122,7 +126,9 @@ For ad-hoc inspection (state summaries, active runs, leases, force-release), use
## Things to look out for
-- **Partition health**: monitor that the `warehouse-sources-queue-partition-management` Temporal schedule is running. Alert on rows landing in DEFAULT partitions (means partition creation failed).
+- **Partition health**: monitor that the `warehouse-sources-queue-partition-management-schedule` Temporal schedule is running, because a run that never starts cannot alert.
+ The job posts to Slack when an upcoming partition is missing or retention is stuck.
+ Rows for today in a DEFAULT partition need no action, because retention deletes them.
- **Poll duration vs lease TTL**: leases are claimed when the poll query starts, so a poll slower than half the 300s TTL hands groups over mostly expired; the consumer logs `poll_duration_approaching_lease_ttl` when this starts happening.
## Generic jobs (phase 1)
diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.py
index 4853a8341fb8..00c7fb14170f 100644
--- a/products/warehouse_sources_queue/backend/core/jobs_db.py
+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py
@@ -74,9 +74,12 @@ PARTITION_PRUNING_INTERVAL = "14 days"
# Oldest a batch may be and still be claimed or recovery-swept. MUST stay below
# the retention window (RETENTION_DAYS in
-# posthog/temporal/warehouse_sources_queue_partition_management/activities.py):
-# a claimed batch's extraction parquet must still exist in S3, and the half-day
-# margin absorbs clock skew and sweep timing. Applies only to the outer claim
+# posthog/temporal/warehouse_sources_queue_partition_management/activities.py),
+# because that job fails and drops old batches on the assumption that no
+# consumer can still claim them. The half-day margin absorbs clock skew and
+# sweep timing. It MUST also stay below the warehouse bucket's lifecycle rule,
+# which deletes extraction parquet 8 days after upload, so that a claimed
+# batch's file still exists. Applies only to the outer claim
# candidates and the recovery sweep — never to the head-of-line/failed-run/
# schema-busy gates, which must keep seeing rows aged past this window for as
# long as they exist.