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.

feat(dags): make old events cleanup a launchable manual job (#113306)

Paweł Szczur4722b943c30c
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 7d00b6a7c8fe..c87aabc231a0 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -238,7 +238,7 @@ 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 a named set of teams, 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 manual run names, and every other personal-data table already expires sooner under its own TTL.
## Adding a table
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index dfe76ff71895..fb2babb5731d 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -119,30 +119,13 @@ class SweepTargetsConfig(dagster.Config):
class MonthlyCleanupConfig(dagster.Config):
team_ids: list[int] = pydantic.Field(
- default_factory=lambda: [
- 9229,
- 10761,
- 19934,
- 41817,
- 9230,
- 9390,
- 19935,
- 41818,
- 9393,
- 22115,
- 7525,
- 9231,
- 19933,
- 54013,
- 9394,
- 12679,
- 19936,
- 41819,
- 9391,
- 54008,
- 29833,
- ],
- description="Team IDs to clean up old events for",
+ min_length=1,
+ description="Team IDs to clean up old events for. Required: every run names its teams explicitly.",
+ )
+ partitions: list[int] = pydantic.Field(
+ min_length=1,
+ description="Events partitions to clean up, as YYYYMM (e.g. [202407]). Required: the run deletes only "
+ "in these months, and only where old rows for the teams exist.",
)
min_age_months: int = pydantic.Field(
default=13,
@@ -150,6 +133,13 @@ class MonthlyCleanupConfig(dagster.Config):
)
+@frozen
+class OldEventsCleanupPlan:
+ team_ids: list[int]
+ partitions: list[int]
+ min_age_months: int
+
+
# Reads only team_id, person_id, timestamp, uuid and inserted_at, which every registered target
# declares. Shared with the post-sweep count so what gets verified is exactly what got deleted.
#
@@ -1249,10 +1239,11 @@ def find_partitions_to_cleanup(
context: dagster.OpExecutionContext,
config: MonthlyCleanupConfig,
cluster: dagster.ResourceParam[ClickhouseCluster],
-) -> list[int]:
- """Find partitions that contain old events for the specified teams."""
+) -> OldEventsCleanupPlan:
+ """Find which of the requested partitions contain old events for the specified teams."""
parameters = {
"team_ids": config.team_ids,
+ "partitions": config.partitions,
"min_age_months": config.min_age_months,
}
@@ -1264,11 +1255,12 @@ def find_partitions_to_cleanup(
SELECT DISTINCT toYYYYMM(timestamp) as partition
FROM {placement.target.data_table}
WHERE team_id IN %(team_ids)s
+ AND toYYYYMM(timestamp) IN %(partitions)s
AND age('month', timestamp, now()) >= %(min_age_months)s
"""
results = placement.cluster.map_one_host_per_shard(Query(query, parameters=parameters)).result()
found.update(partition for rows in results.values() for (partition,) in rows)
- partitions = sorted(found, reverse=True)
+ partitions = sorted(found & set(config.partitions), reverse=True)
context.add_output_metadata(
{
@@ -1278,30 +1270,30 @@ def find_partitions_to_cleanup(
}
)
- return partitions
+ return OldEventsCleanupPlan(team_ids=config.team_ids, partitions=partitions, min_age_months=config.min_age_months)
@dagster.op
def cleanup_old_events_by_partition(
context: dagster.OpExecutionContext,
- config: MonthlyCleanupConfig,
cluster: dagster.ResourceParam[ClickhouseCluster],
- partitions: list[int],
+ plan: OldEventsCleanupPlan,
) -> None:
- """Delete old events from the specified teams in each partition."""
- if not partitions:
+ """Delete old events from the plan's teams in each of the plan's partitions."""
+ if not plan.partitions:
context.log.info("No partitions found to clean up")
return
- total_partitions = len(partitions)
+ total_partitions = len(plan.partitions)
# Both events tables partition by toYYYYMM(timestamp), so the same partition list applies;
# deleting IN PARTITION on a partition a table doesn't have is a no-op.
#
# Events only, deliberately: this enforces a multi-year retention floor for a named set of
# teams, and every other personal-data table already expires sooner under its own TTL.
placements = resolve_placements(cluster, EVENTS_TARGETS)
+ reuse_floor = _mutation_reuse_floor(cluster)
- for idx, partition in enumerate(partitions, 1):
+ for idx, partition in enumerate(plan.partitions, 1):
context.log.info(f"Processing partition {partition} ({idx}/{total_partitions})")
for placement in placements:
@@ -1312,11 +1304,12 @@ def cleanup_old_events_by_partition(
AND age('month', timestamp, now()) >= %(min_age_months)s
""",
parameters={
- "team_ids": config.team_ids,
- "min_age_months": config.min_age_months,
+ "team_ids": plan.team_ids,
+ "min_age_months": plan.min_age_months,
},
partition=str(partition),
settings={"lightweight_deletes_sync": 0},
+ reuse_since=reuse_floor,
patch_parts=placement.target.uses_patch_parts,
)
@@ -1337,23 +1330,12 @@ def cleanup_old_events_by_partition(
context.add_output_metadata(
{
"partitions_processed": dagster.MetadataValue.int(total_partitions),
- "team_ids": dagster.MetadataValue.text(", ".join(str(tid) for tid in config.team_ids)),
+ "team_ids": dagster.MetadataValue.text(", ".join(str(tid) for tid in plan.team_ids)),
}
)
@dagster.job(tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
def monthly_old_events_cleanup_job():
- """Monthly job to clean up old events for specific teams."""
- partitions = find_partitions_to_cleanup()
- cleanup_old_events_by_partition(partitions)
-
-
- job=monthly_old_events_cleanup_job,
- cron_schedule="0 0 1 * *",
- execution_timezone="UTC",
-)
-def monthly_old_events_cleanup_schedule():
- """Run monthly cleanup on the 1st of each month at midnight UTC."""
- return dagster.RunRequest()
+ """Delete old events for the named teams in the named partitions. Launched by hand, with no schedule."""
+ cleanup_old_events_by_partition(find_partitions_to_cleanup())
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index bc37b302b030..f4a46dee4ee1 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -37,6 +37,7 @@ defs = dagster.Definitions(
drop_materialized_column.drop_materialized_column,
deletes.deletes_job,
deletes.manual_deletes_job,
+ deletes.monthly_old_events_cleanup_job,
export_query_log_archive_to_s3.export_query_log_archive_to_s3,
backfill_materialized_column.backfill_materialized_column,
fix_person_id_overrides.fix_person_id_overrides_job,
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 5e97e132359f..29a24dd56ca7 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -606,13 +606,15 @@ def test_find_partitions_to_cleanup(cluster: ClickhouseCluster):
cluster.any_host(insert_events).result()
- config = MonthlyCleanupConfig(team_ids=team_ids, min_age_months=13)
+ config = MonthlyCleanupConfig(
+ team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
+ )
context = build_op_context()
- partitions = find_partitions_to_cleanup(context, config, cluster)
+ plan = find_partitions_to_cleanup(context, config, cluster)
- assert len(partitions) > 0
- for partition in partitions:
+ assert len(plan.partitions) > 0
+ for partition in plan.partitions:
partition_date = datetime.strptime(str(partition), "%Y%m")
months_diff = (now.year - partition_date.year) * 12 + (now.month - partition_date.month)
assert months_diff >= 13
@@ -671,11 +673,13 @@ def test_cleanup_old_events_by_partition(cluster: ClickhouseCluster):
assert old_count_before == len(old_events)
assert recent_count_before == len(recent_events)
- config = MonthlyCleanupConfig(team_ids=team_ids, min_age_months=13)
+ config = MonthlyCleanupConfig(
+ team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
+ )
context = build_op_context()
- partitions = find_partitions_to_cleanup(context, config, cluster)
- cleanup_old_events_by_partition(context, config, cluster, partitions)
+ plan = find_partitions_to_cleanup(context, config, cluster)
+ cleanup_old_events_by_partition(context, cluster, plan)
old_count_after, recent_count_after = cluster.any_host(count_events_by_age).result()
assert old_count_after == 0
@@ -711,11 +715,13 @@ def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snap
cluster.any_host(insert_events).result()
- config = MonthlyCleanupConfig(team_ids=team_ids, min_age_months=13)
+ config = MonthlyCleanupConfig(
+ team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
+ )
context = build_op_context()
- partitions = find_partitions_to_cleanup(context, config, cluster)
- assert len(partitions) > 0
+ plan = find_partitions_to_cleanup(context, config, cluster)
+ assert len(plan.partitions) > 0
captured_delete_statements = []
original_call = LightweightDeleteMutationRunner.__call__
@@ -727,7 +733,7 @@ def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snap
return original_call(self, client)
with patch.object(LightweightDeleteMutationRunner, "__call__", capture_delete_statement):
- cleanup_old_events_by_partition(context, config, cluster, partitions)
+ cleanup_old_events_by_partition(context, cluster, plan)
assert len(captured_delete_statements) > 0
@@ -738,6 +744,7 @@ def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snap
def test_monthly_old_events_cleanup_job(cluster: ClickhouseCluster):
now = datetime.now()
old_timestamp = now - timedelta(days=400)
+ older_unrequested_timestamp = now - timedelta(days=460)
recent_timestamp = now - timedelta(days=30)
team_ids = [300, 301, 302]
@@ -746,6 +753,11 @@ def test_monthly_old_events_cleanup_job(cluster: ClickhouseCluster):
for team_id in team_ids
for i in range(100)
]
+ older_unrequested_events = [
+ (team_id, f"older_{team_id}_{i}", UUID(int=team_id * 1000 + 200 + i), older_unrequested_timestamp)
+ for team_id in team_ids
+ for i in range(20)
+ ]
recent_events = [
(team_id, f"recent_{team_id}_{i}", UUID(int=team_id * 1000 + 100 + i), recent_timestamp)
for team_id in team_ids
@@ -757,36 +769,51 @@ def test_monthly_old_events_cleanup_job(cluster: ClickhouseCluster):
"""INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp)
VALUES
""",
- old_events + recent_events,
+ old_events + older_unrequested_events + recent_events,
)
cluster.any_host(insert_events).result()
- def count_all_events(client: Client) -> int:
- result = client.execute(
+ old_partition = int(old_timestamp.strftime("%Y%m"))
+ older_unrequested_partition = int(older_unrequested_timestamp.strftime("%Y%m"))
+ recent_partition = int(recent_timestamp.strftime("%Y%m"))
+
+ def count_events_by_partition(client: Client) -> dict[int, int]:
+ rows = client.execute(
f"""
- SELECT count(*)
+ SELECT toYYYYMM(timestamp), count(*)
FROM writable_events
WHERE team_id IN ({", ".join(str(t) for t in team_ids)})
+ GROUP BY toYYYYMM(timestamp)
"""
)
- return result[0][0]
+ return dict(rows)
- events_before = cluster.any_host(count_all_events).result()
- assert events_before == len(old_events) + len(recent_events)
+ assert cluster.any_host(count_events_by_partition).result() == {
+ old_partition: len(old_events),
+ older_unrequested_partition: len(older_unrequested_events),
+ recent_partition: len(recent_events),
+ }
monthly_old_events_cleanup_job.execute_in_process(
run_config={
"ops": {
- "find_partitions_to_cleanup": {"config": {"team_ids": team_ids, "min_age_months": 13}},
- "cleanup_old_events_by_partition": {"config": {"team_ids": team_ids, "min_age_months": 13}},
+ "find_partitions_to_cleanup": {
+ "config": {
+ "team_ids": team_ids,
+ "partitions": [old_partition],
+ "min_age_months": 13,
+ }
+ },
}
},
resources={"cluster": cluster},
)
- events_after = cluster.any_host(count_all_events).result()
- assert events_after == len(recent_events)
+ assert cluster.any_host(count_events_by_partition).result() == {
+ older_unrequested_partition: len(older_unrequested_events),
+ recent_partition: len(recent_events),
+ }
def _insert_pending_deletes(table: PendingDeletesTable, client: Client, count: int = 5, first_id: int = 0) -> None: