: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(dags): schedule the old events cleanup monthly in EU (#113438)
Paweł Szczurdec053cb9ec3
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 1443550e03a3..75c3d2552ce5 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -252,7 +252,9 @@ When one of those runs starts during a copy, the shard stops, and its error name`_fetch_stats` counts only the events tables. It feeds `AUTO_APPROVE_MAX_EVENTS`, a cost heuristic rather than a completeness claim, so a request auto-approved as small may move somewhat more rows than measured.-`cleanup_old_events_by_partition` stays events-only. It enforces a multi-year retention floor for the teams and partitions each manual run names, and every other personal-data table already expires sooner under its own TTL.+`cleanup_old_events_by_partition` stays events-only. It enforces a multi-year retention floor for the teams and partitions each run names, and every other personal-data table already expires sooner under its own TTL.+In EU, `eu_monthly_old_events_cleanup_schedule` runs it monthly for a fixed team list, over every partition from 202001 through the newest month with 13-month-old rows.+It is stopped by default. It leaves events dated before 2020 in place, because `sharded_events_json` keeps them in its 202001 partition and the schedule matches on the event's own month.## Adding a tablediff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex fb2babb5731d..398eb8f51144 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -117,6 +117,9 @@ class SweepTargetsConfig(dagster.Config):)+OLD_EVENTS_MIN_AGE_MONTHS = 13++class MonthlyCleanupConfig(dagster.Config):team_ids: list[int] = pydantic.Field(min_length=1,@@ -128,7 +131,7 @@ class MonthlyCleanupConfig(dagster.Config):"in these months, and only where old rows for the teams exist.",)min_age_months: int = pydantic.Field(- default=13,+ default=OLD_EVENTS_MIN_AGE_MONTHS,description="Minimum age in months for events to be deleted",)@@ -1337,5 +1340,66 @@ def cleanup_old_events_by_partition(@dagster.job(tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})def monthly_old_events_cleanup_job():- """Delete old events for the named teams in the named partitions. Launched by hand, with no schedule."""+ """Delete old events for the named teams in the named partitions."""cleanup_old_events_by_partition(find_partitions_to_cleanup())+++EU_OLD_EVENTS_CLEANUP_TEAM_IDS: tuple[int, ...] = (+ 9229,+ 10761,+ 19934,+ 41817,+ 9230,+ 9390,+ 19935,+ 41818,+ 9393,+ 22115,+ 7525,+ 9231,+ 19933,+ 54013,+ 9394,+ 12679,+ 19936,+ 41819,+ 9391,+ 54008,+ 29833,+)++# sharded_events_json clamps every earlier timestamp into its 202001 partition. The schedule leaves+# events dated before 2020 in place, because a request for their month misses that json partition.+OLD_EVENTS_CLEANUP_FIRST_PARTITION = 202001+++def partitions_through_cutoff(now: datetime, min_age_months: int) -> list[int]:+ """Every YYYYMM from the first partition through the newest month that holds rows at least min_age_months old."""+ first_year, first_month = divmod(OLD_EVENTS_CLEANUP_FIRST_PARTITION, 100)+ first = first_year * 12 + first_month - 1+ cutoff = now.year * 12 + now.month - 1 - min_age_months+ return [(month // 12) * 100 + month % 12 + 1 for month in range(first, cutoff + 1)]+++ job=monthly_old_events_cleanup_job,+ cron_schedule="0 0 1 * *",+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.STOPPED,+)+def eu_monthly_old_events_cleanup_schedule(context: dagster.ScheduleEvaluationContext) -> dagster.RunRequest:+ scheduled_at = context.scheduled_execution_time+ return dagster.RunRequest(+ run_key=scheduled_at.strftime("%Y%m"),+ run_config={+ "ops": {+ "find_partitions_to_cleanup": {+ "config": {+ "team_ids": list(EU_OLD_EVENTS_CLEANUP_TEAM_IDS),+ "partitions": partitions_through_cutoff(scheduled_at, OLD_EVENTS_MIN_AGE_MONTHS),+ "min_age_months": OLD_EVENTS_MIN_AGE_MONTHS,+ }+ }+ }+ },+ )diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex fd0e019fc88d..230babd9366b 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -1,3 +1,5 @@+from django.conf import settings+import dagsterfrom posthog.dags import (@@ -70,6 +72,8 @@ defs = dagster.Definitions(part_breaker.break_oversized_parts_schedule,data_deletion_requests.auto_approve_deletion_requests_schedule,warehouse_object_reads_daily.warehouse_object_reads_daily_schedule,+ # The schedule's team IDs name EU teams. The same IDs name other teams in US.+ *([deletes.eu_monthly_old_events_cleanup_schedule] if settings.CLOUD_DEPLOYMENT == "EU" else []),],sensors=[clickhouse_cleanup.run_cleanup_sweep_after_deletes,diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex 29a24dd56ca7..06d41263bab5 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -19,6 +19,7 @@ from posthog.dags.deletes import (_DELETE_PREDICATE,_SURVIVOR_COUNT_ATTEMPTS,DELETES_RUN_CONFIG,+ EU_OLD_EVENTS_CLEANUP_TEAM_IDS,AdhocEventDeletesDictionary,AdhocEventDeletesTable,DeleteConfig,@@ -32,6 +33,7 @@ from posthog.dags.deletes import (cleanup_old_events_by_partition,deletes_job,ensure_no_concurrent_deletes_run,+ eu_monthly_old_events_cleanup_schedule,find_partitions_to_cleanup,manual_deletes_job,mark_deletions_verified,@@ -816,6 +818,33 @@ def test_monthly_old_events_cleanup_job(cluster: ClickhouseCluster):}+ "scheduled_at, newest_partition",+ [+ (datetime(2026, 11, 1, tzinfo=UTC), 202510),+ (datetime(2027, 1, 1, tzinfo=UTC), 202512),+ (datetime(2027, 2, 1, tzinfo=UTC), 202601),+ ],+)+def test_eu_monthly_old_events_cleanup_schedule_requests_every_month_through_cutoff(+ scheduled_at: datetime, newest_partition: int+):+ with dagster.build_schedule_context(scheduled_execution_time=scheduled_at) as context:+ run_request = eu_monthly_old_events_cleanup_schedule(context)++ assert isinstance(run_request, dagster.RunRequest)+ config = run_request.run_config["ops"]["find_partitions_to_cleanup"]["config"]+ assert config["team_ids"] == list(EU_OLD_EVENTS_CLEANUP_TEAM_IDS)+ assert config["min_age_months"] == 13+ partitions = config["partitions"]+ assert partitions[0] == 202001+ assert partitions[-1] == newest_partition+ assert all(+ later == (earlier + 1 if earlier % 100 < 12 else earlier + 89)+ for earlier, later in zip(partitions, partitions[1:])+ )++def _insert_pending_deletes(table: PendingDeletesTable, client: Client, count: int = 5, first_id: int = 0) -> None:client.execute(table.populate_query,