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): drive the old events cleanup from admin retention settings (#114419)

Paweł Szczur4720989d063d
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 75c3d2552ce5..e1e6582f53e7 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -252,9 +252,24 @@ 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 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.
+`cleanup_old_events_by_partition` stays events-only. It enforces the events retention that staff set for each team, and every other personal-data table already expires sooner under its own TTL.
+It deletes a month only when every event in it is older than the retention. A month that is only partly past the retention waits for a later run, for manual runs too.
+
+Staff set the retention in Django admin, on the team and organization pages:
+
+- `OrganizationEventsRetentionConfig` holds the organization's default, minimum and maximum months.
+- `TeamEventsRetentionConfig` holds a team's own months, which must fall within its organization's range. Saving an organization range that excludes an existing team value fails until that team changes.
+- A team's effective retention is its own value, else its organization's default. A team with neither keeps all its events.
+- This setting is separate from `Team.event_retention_months`, which the billing plan sets and which only hides older events from queries.
+
+`monthly_old_events_cleanup_job` has two steps:
+
+- `plan_old_events_cleanup` reads every team's effective retention when the run starts and logs each one as organization, team and months. It then finds the months that hold events for each team and keeps the ones entirely past that team's retention. It logs the teams due in each month.
+- `cleanup_old_events_by_partition` deletes each planned month for the teams due in that month only. A team with 13 months and a team with 18 months share the older months, and the 13-month team also has months of its own.
+
+A manual run can narrow the plan with `team_ids` and `partitions`. A listed team with no retention is ignored.
+`monthly_old_events_cleanup_schedule` starts one run on the 1st of each month, in every region, and skips when no retention is set. It is stopped by default. The job shares the `deletes_job` run queue, so it does not mutate the same partitions at the same time.
+`sharded_events_json` keeps events dated before 2020, because it stores them in its 202001 partition and the delete addresses the event's own month.
## Adding a table
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 398eb8f51144..c1f620e09cdc 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -1,8 +1,9 @@
import abc
import uuid
+from collections import defaultdict
from collections.abc import Callable, Sequence
from dataclasses import dataclass
-from datetime import datetime
+from datetime import UTC, datetime
from functools import partial
from django.conf import settings
@@ -12,6 +13,7 @@ from django.utils import timezone
import dagster
import pydantic
from clickhouse_driver.client import Client
+from dateutil.relativedelta import relativedelta
from more_itertools import chunked
from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
@@ -47,6 +49,7 @@ from posthog.models.deletion_targets import (
surviving_rows_sql,
sweep_clusters,
)
+from posthog.models.events_retention_config import effective_events_retention
from posthog.models.group.sql import GROUPS_TABLE
from posthog.models.person.sql import (
PERSON_DISTINCT_ID2_TABLE,
@@ -117,30 +120,41 @@ class SweepTargetsConfig(dagster.Config):
)
-OLD_EVENTS_MIN_AGE_MONTHS = 13
-
-
class MonthlyCleanupConfig(dagster.Config):
team_ids: list[int] = pydantic.Field(
- min_length=1,
- description="Team IDs to clean up old events for. Required: every run names its teams explicitly.",
+ default_factory=list,
+ description="Only clean up these teams. Empty means every team with an events retention in Django admin. "
+ "A listed team with no events retention is ignored.",
)
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=OLD_EVENTS_MIN_AGE_MONTHS,
- description="Minimum age in months for events to be deleted",
+ default_factory=list,
+ description="Only clean up these months, as YYYYMM (e.g. [202407]). Empty means every month that is due.",
)
@frozen
-class OldEventsCleanupPlan:
+class PartitionCleanup:
+ partition: int
team_ids: list[int]
- partitions: list[int]
- min_age_months: int
+
+
+@frozen
+class OldEventsCleanupPlan:
+ partitions: list[PartitionCleanup]
+
+
+def whole_month_cutoff(now: datetime, retention_months: int) -> datetime:
+ """Start of the month that holds the instant ``retention_months`` before ``now``."""
+ return (now - relativedelta(months=retention_months)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+
+def _yyyymm(moment: datetime) -> int:
+ return moment.year * 100 + moment.month
+
+
+def _start_of_month_after(partition: int) -> datetime:
+ year, month = divmod(partition, 100)
+ return datetime(year, month, 1) + relativedelta(months=1)
# Reads only team_id, person_id, timestamp, uuid and inserted_at, which every registered target
@@ -1238,42 +1252,71 @@ def run_deletes_after_manual_trigger(context: dagster.RunStatusSensorContext) ->
@dagster.op
-def find_partitions_to_cleanup(
+def plan_old_events_cleanup(
context: dagster.OpExecutionContext,
config: MonthlyCleanupConfig,
cluster: dagster.ResourceParam[ClickhouseCluster],
) -> OldEventsCleanupPlan:
- """Find which of the requested partitions contain old events for the specified teams."""
+ """Find every team with an events retention, and for each month the teams whose events in it are all past it."""
+ retention = effective_events_retention()
+ if config.team_ids:
+ if ignored := sorted(set(config.team_ids) - {item.team_id for item in retention}):
+ context.log.info(f"Ignoring teams with no events retention: {ignored}")
+ retention = [item for item in retention if item.team_id in config.team_ids]
+ if not retention:
+ context.log.info("No team has an events retention to enforce")
+ return OldEventsCleanupPlan(partitions=[])
+
+ now = datetime.now(UTC).replace(tzinfo=None)
+ team_cutoffs: dict[int, datetime] = {}
+ for item in retention:
+ team_cutoffs[item.team_id] = whole_month_cutoff(now, item.months)
+ context.log.info(
+ f"org {item.organization_id}, team {item.team_id}, {item.months} months: "
+ f"months before {team_cutoffs[item.team_id]:%Y-%m} are due"
+ )
+
+ partition_filter = "AND toYYYYMM(timestamp) IN %(partitions)s" if config.partitions else ""
parameters = {
- "team_ids": config.team_ids,
+ "team_ids": sorted(team_cutoffs),
"partitions": config.partitions,
- "min_age_months": config.min_age_months,
+ "cutoff": max(team_cutoffs.values()),
}
-
- # Each events table is read on every shard of its own cluster: a month can hold old rows in one
- # table or shard and none in the others, and the cleanup only visits the months found here.
- found: set[int] = set()
+ # Each events table is read on every shard of its own cluster: a month can hold events in one
+ # table or shard and none in the others.
+ team_months: set[tuple[int, int]] = set()
for placement in resolve_placements(cluster, EVENTS_TARGETS):
query = f"""
- SELECT DISTINCT toYYYYMM(timestamp) as partition
+ SELECT DISTINCT team_id, 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
+ AND timestamp < %(cutoff)s
+ {partition_filter}
"""
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 & set(config.partitions), reverse=True)
+ team_months.update((team_id, partition) for rows in results.values() for team_id, partition in rows)
+
+ teams_by_partition: dict[int, list[int]] = defaultdict(list)
+ for team_id, partition in sorted(team_months):
+ if partition < _yyyymm(team_cutoffs[team_id]):
+ teams_by_partition[partition].append(team_id)
+
+ plan = OldEventsCleanupPlan(
+ partitions=[
+ PartitionCleanup(partition=partition, team_ids=team_ids)
+ for partition, team_ids in sorted(teams_by_partition.items(), reverse=True)
+ ]
+ )
+ for partition_cleanup in plan.partitions:
+ context.log.info(f"{partition_cleanup.partition}: teams {partition_cleanup.team_ids}")
context.add_output_metadata(
{
- "partitions_found": dagster.MetadataValue.int(len(partitions)),
- "partitions": dagster.MetadataValue.text(", ".join(str(p) for p in partitions)),
- "team_ids": dagster.MetadataValue.text(", ".join(str(tid) for tid in config.team_ids)),
+ "teams": dagster.MetadataValue.int(len(team_cutoffs)),
+ "partitions": dagster.MetadataValue.int(len(plan.partitions)),
}
)
-
- return OldEventsCleanupPlan(team_ids=config.team_ids, partitions=partitions, min_age_months=config.min_age_months)
+ return plan
@dagster.op
@@ -1282,35 +1325,36 @@ def cleanup_old_events_by_partition(
cluster: dagster.ResourceParam[ClickhouseCluster],
plan: OldEventsCleanupPlan,
) -> None:
- """Delete old events from the plan's teams in each of the plan's partitions."""
+ """Delete each planned month's events for the teams the plan lists for that month."""
if not plan.partitions:
context.log.info("No partitions found to clean up")
return
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.
+ # deleting IN PARTITION on a partition a table doesn't have is a no-op. sharded_events_json
+ # clamps timestamps before 2020 into its 202001 partition, so it keeps events dated before 2020.
#
- # 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.
+ # Events only, deliberately: this enforces a multi-year retention floor for the teams a run
+ # names, 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(plan.partitions, 1):
- context.log.info(f"Processing partition {partition} ({idx}/{total_partitions})")
+ for idx, item in enumerate(plan.partitions, 1):
+ context.log.info(f"Deleting {item.partition} for teams {item.team_ids} ({idx}/{total_partitions})")
for placement in placements:
delete_mutation_runner = LightweightDeleteMutationRunner(
table=placement.target.data_table,
predicate="""
team_id IN %(team_ids)s
- AND age('month', timestamp, now()) >= %(min_age_months)s
+ AND timestamp < %(before)s
""",
parameters={
- "team_ids": plan.team_ids,
- "min_age_months": plan.min_age_months,
+ "team_ids": item.team_ids,
+ "before": _start_of_month_after(item.partition),
},
- partition=str(partition),
+ partition=str(item.partition),
settings={"lightweight_deletes_sync": 0},
reuse_since=reuse_floor,
patch_parts=placement.target.uses_patch_parts,
@@ -1328,57 +1372,27 @@ def cleanup_old_events_by_partition(
}
).result()
- context.log.info(f"Completed deletion for partition {partition}")
+ context.log.info(f"Completed deletion for partition {item.partition}")
context.add_output_metadata(
{
"partitions_processed": dagster.MetadataValue.int(total_partitions),
- "team_ids": dagster.MetadataValue.text(", ".join(str(tid) for tid in plan.team_ids)),
+ "team_ids": dagster.MetadataValue.text(
+ ", ".join(str(tid) for tid in sorted({tid for item in plan.partitions for tid in item.team_ids}))
+ ),
}
)
[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
-def monthly_old_events_cleanup_job():
- """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,
+ tags={
+ "owner": JobOwners.TEAM_CLICKHOUSE.value,
+ "deletes_job_concurrency": "v1",
+ }
)
-
-# 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)]
+def monthly_old_events_cleanup_job():
+ """Delete events past each team's events retention set in Django admin, a whole month at a time."""
+ cleanup_old_events_by_partition(plan_old_events_cleanup())
@dagster.schedule(
@@ -1387,19 +1401,9 @@ def partitions_through_cutoff(now: datetime, min_age_months: int) -> list[int]:
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,
- }
- }
- }
- },
- )
+def monthly_old_events_cleanup_schedule(
+ context: dagster.ScheduleEvaluationContext,
+) -> dagster.RunRequest | dagster.SkipReason:
+ if not effective_events_retention():
+ return dagster.SkipReason("No team or organization has an events retention set")
+ return dagster.RunRequest(run_key=f"{context.scheduled_execution_time:%Y%m}")
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index 230babd9366b..a0cd9d2806a2 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -1,5 +1,3 @@
-from django.conf import settings
-
import dagster
from posthog.dags import (
@@ -72,8 +70,7 @@ 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 []),
+ deletes.monthly_old_events_cleanup_schedule,
],
sensors=[
clickhouse_cleanup.run_cleanup_sweep_after_deletes,
diff --git a/posthog/dags/tests/__snapshots__/test_deletes.ambr b/posthog/dags/tests/__snapshots__/test_deletes.ambr
index a5b439521d18..b52792335212 100644
--- a/posthog/dags/tests/__snapshots__/test_deletes.ambr
+++ b/posthog/dags/tests/__snapshots__/test_deletes.ambr
@@ -2,15 +2,15 @@
# name: test_cleanup_old_events_delete_query_format
list([
'''
- DELETE FROM posthog_test.sharded_events IN PARTITION '202408' WHERE
+ DELETE FROM posthog_test.sharded_events IN PARTITION '202406' WHERE
team_id IN %(team_ids)s
- AND age('month', timestamp, now()) >= %(min_age_months)s
+ AND timestamp < %(before)s
''',
'''
- DELETE FROM posthog_test.sharded_events_json IN PARTITION '202408' WHERE
+ DELETE FROM posthog_test.sharded_events_json IN PARTITION '202406' WHERE
team_id IN %(team_ids)s
- AND age('month', timestamp, now()) >= %(min_age_months)s
+ AND timestamp < %(before)s
''',
])
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 06d41263bab5..c9633f54a1cc 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -12,6 +12,7 @@ from django.conf import settings as django_settings
import dagster
from clickhouse_driver import Client
from dagster import build_op_context
+from dateutil.relativedelta import relativedelta
from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner, NodeRole, Query
from posthog.dags.common.staged_dictionary import create_on_every_cluster
@@ -19,11 +20,12 @@ from posthog.dags.deletes import (
_DELETE_PREDICATE,
_SURVIVOR_COUNT_ATTEMPTS,
DELETES_RUN_CONFIG,
- EU_OLD_EVENTS_CLEANUP_TEAM_IDS,
AdhocEventDeletesDictionary,
AdhocEventDeletesTable,
DeleteConfig,
MonthlyCleanupConfig,
+ OldEventsCleanupPlan,
+ PartitionCleanup,
PendingDeletesDictionary,
PendingDeletesTable,
StagedDictionary,
@@ -33,11 +35,11 @@ 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,
monthly_old_events_cleanup_job,
+ monthly_old_events_cleanup_schedule,
+ plan_old_events_cleanup,
resolve_sweep_targets,
run_deletes_after_manual_trigger,
)
@@ -46,7 +48,10 @@ from posthog.dags.tests.conftest import insert_flag_evaluations
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.deletion_targets import DEFAULT_DELETION_TARGETS, EVENTS, PERSONAL_DATA_TARGETS, TargetPlacement
from posthog.models.event.sql import EVENTS_DATA_TABLE
+from posthog.models.events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig
+from posthog.models.organization import Organization
from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
+from posthog.models.team import Team
def surviving_flag_evaluations(client: Client) -> set[tuple[int, UUID, UUID]]:
@@ -577,115 +582,90 @@ def test_full_job_deletes_events_queued_in_postgres(cluster: ClickhouseCluster):
assert not AsyncDeletion.objects.filter(deletion_type=DeletionType.Event, delete_verified_at__isnull=True).exists()
-def test_find_partitions_to_cleanup(cluster: ClickhouseCluster):
- from dagster import build_op_context
-
- now = datetime.now()
- old_timestamp = now - timedelta(days=400)
- recent_timestamp = now - timedelta(days=30)
-
- team_ids = [100, 101, 102]
- events = []
- for team_id in team_ids:
- events.extend(
- [(team_id, f"distinct_id_{team_id}_{i}", UUID(int=team_id * 1000 + i), old_timestamp) for i in range(10)]
- )
- events.extend(
- [
- (team_id, f"distinct_id_{team_id}_{i}", UUID(int=team_id * 1000 + 100 + i), recent_timestamp)
- for i in range(5)
- ]
- )
+def _mid_month(months_ago: int) -> datetime:
+ return (datetime.now() - relativedelta(months=months_ago)).replace(
+ day=15, hour=12, minute=0, second=0, microsecond=0
+ )
- def insert_events(client: Client) -> None:
- client.execute(
- """INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp)
- VALUES
- """,
- events,
- )
- cluster.any_host(insert_events).result()
+def _first_hour_of_month(months_ago: int) -> datetime:
+ return (datetime.now() - relativedelta(months=months_ago)).replace(day=1, hour=1, minute=0, second=0, microsecond=0)
- config = MonthlyCleanupConfig(
- team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
- )
- context = build_op_context()
- plan = find_partitions_to_cleanup(context, config, cluster)
+def _partition(timestamp: datetime) -> int:
+ return int(timestamp.strftime("%Y%m"))
- 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
+def _insert_events(cluster: ClickhouseCluster, events: list[tuple[int, str, UUID, datetime]]) -> None:
+ def insert(client: Client) -> None:
+ client.execute("INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp) VALUES", events)
-def test_cleanup_old_events_by_partition(cluster: ClickhouseCluster):
- from dagster import build_op_context
-
- now = datetime.now()
- old_timestamp = now - timedelta(days=400)
- recent_timestamp = now - timedelta(days=30)
-
- team_ids = [200, 201]
- old_events = [
- (team_id, f"old_{team_id}_{i}", UUID(int=team_id * 1000 + i), old_timestamp)
- for team_id in team_ids
- for i in range(50)
- ]
- recent_events = [
- (team_id, f"recent_{team_id}_{i}", UUID(int=team_id * 1000 + 100 + i), recent_timestamp)
- for team_id in team_ids
- for i in range(50)
+ cluster.any_host(insert).result()
+
+
+def _events(team_id: int, timestamp: datetime, first_uuid: int, count: int) -> list[tuple[int, str, UUID, datetime]]:
+ return [
+ (team_id, f"user_{team_id}_{i}", UUID(int=team_id * 100_000 + first_uuid + i), timestamp) for i in range(count)
]
- def insert_events(client: Client) -> None:
- client.execute(
- """INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp)
- VALUES
- """,
- old_events + recent_events,
+
+def _count_by_team_and_partition(cluster: ClickhouseCluster, team_ids: list[int]) -> dict[tuple[int, int], int]:
+ def count(client: Client) -> dict[tuple[int, int], int]:
+ rows = client.execute(
+ "SELECT team_id, toYYYYMM(timestamp), count() FROM writable_events WHERE team_id IN %(team_ids)s "
+ "GROUP BY team_id, toYYYYMM(timestamp)",
+ {"team_ids": team_ids},
)
+ return {(team_id, partition): events for team_id, partition, events in rows}
- cluster.any_host(insert_events).result()
+ return cluster.any_host(count).result()
- def count_events_by_age(client: Client) -> tuple[int, int]:
- old_result = client.execute(
- f"""
- SELECT count(*)
- FROM writable_events
- WHERE team_id IN ({", ".join(str(t) for t in team_ids)})
- AND age('month', timestamp, now()) >= 13
- """
- )
- recent_result = client.execute(
- f"""
- SELECT count(*)
- FROM writable_events
- WHERE team_id IN ({", ".join(str(t) for t in team_ids)})
- AND age('month', timestamp, now()) < 13
- """
- )
- return (old_result[0][0], recent_result[0][0])
- old_count_before, recent_count_before = cluster.any_host(count_events_by_age).result()
- assert old_count_before == len(old_events)
- assert recent_count_before == len(recent_events)
+def _teams_with_13_and_18_months() -> tuple[Team, Team, Team]:
+ organization = Organization.objects.create(name="Retention")
+ thirteen = Team.objects.create(organization=organization, name="13 months")
+ eighteen = Team.objects.create(organization=organization, name="18 months")
+ no_retention = Team.objects.create(organization=organization, name="No retention")
+ TeamEventsRetentionConfig.objects.create(team=thirteen, events_retention_months=13)
+ TeamEventsRetentionConfig.objects.create(team=eighteen, events_retention_months=18)
+ return thirteen, eighteen, no_retention
+
- config = MonthlyCleanupConfig(
- team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
+def test_plan_old_events_cleanup_lists_the_due_teams_per_month(cluster: ClickhouseCluster):
+ thirteen, eighteen, no_retention = _teams_with_13_and_18_months()
+ _insert_events(
+ cluster,
+ _events(thirteen.id, _mid_month(15), 0, 3)
+ + _events(thirteen.id, _mid_month(20), 100, 4)
+ + _events(thirteen.id, _first_hour_of_month(13), 200, 5)
+ + _events(eighteen.id, _mid_month(15), 0, 6)
+ + _events(eighteen.id, _mid_month(20), 100, 7)
+ + _events(eighteen.id, _first_hour_of_month(18), 200, 8)
+ + _events(no_retention.id, _mid_month(20), 0, 9),
)
context = build_op_context()
- plan = find_partitions_to_cleanup(context, config, cluster)
- cleanup_old_events_by_partition(context, cluster, plan)
+ plan = plan_old_events_cleanup(context, MonthlyCleanupConfig(), cluster)
- old_count_after, recent_count_after = cluster.any_host(count_events_by_age).result()
- assert old_count_after == 0
- assert recent_count_after == len(recent_events)
+ assert plan == OldEventsCleanupPlan(
+ partitions=[
+ PartitionCleanup(partition=_partition(_mid_month(15)), team_ids=[thirteen.id]),
+ PartitionCleanup(partition=_partition(_mid_month(20)), team_ids=[thirteen.id, eighteen.id]),
+ ]
+ )
+
+ only_oldest = plan_old_events_cleanup(
+ context, MonthlyCleanupConfig(partitions=[_partition(_mid_month(20))]), cluster
+ )
+ assert [item.partition for item in only_oldest.partitions] == [_partition(_mid_month(20))]
+
+ only_eighteen = plan_old_events_cleanup(
+ context, MonthlyCleanupConfig(team_ids=[eighteen.id, no_retention.id]), cluster
+ )
+ assert only_eighteen == OldEventsCleanupPlan(
+ partitions=[PartitionCleanup(partition=_partition(_mid_month(20)), team_ids=[eighteen.id])]
+ )
@pytest.mark.django_db
@@ -693,37 +673,9 @@ def test_cleanup_old_events_by_partition(cluster: ClickhouseCluster):
def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snapshot):
from unittest.mock import patch
- from dagster import build_op_context
-
from posthog.clickhouse.cluster import LightweightDeleteMutationRunner
- now = datetime.now()
- old_timestamp = now - timedelta(days=400)
-
- team_ids = [400, 401]
- old_events = [
- (team_id, f"old_{team_id}_{i}", UUID(int=team_id * 1000 + i), old_timestamp)
- for team_id in team_ids
- for i in range(10)
- ]
-
- def insert_events(client: Client) -> None:
- client.execute(
- """INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp)
- VALUES
- """,
- old_events,
- )
-
- cluster.any_host(insert_events).result()
-
- config = MonthlyCleanupConfig(
- team_ids=team_ids, partitions=[int(old_timestamp.strftime("%Y%m"))], min_age_months=13
- )
- context = build_op_context()
-
- plan = find_partitions_to_cleanup(context, config, cluster)
- assert len(plan.partitions) > 0
+ plan = OldEventsCleanupPlan(partitions=[PartitionCleanup(partition=202406, team_ids=[400, 401])])
captured_delete_statements = []
original_call = LightweightDeleteMutationRunner.__call__
@@ -735,7 +687,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, cluster, plan)
+ cleanup_old_events_by_partition(build_op_context(), cluster, plan)
assert len(captured_delete_statements) > 0
@@ -744,105 +696,41 @@ def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snap
@pytest.mark.django_db
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]
- old_events = [
- (team_id, f"old_{team_id}_{i}", UUID(int=team_id * 1000 + i), old_timestamp)
- 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
- for i in range(50)
- ]
-
- def insert_events(client: Client) -> None:
- client.execute(
- """INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp)
- VALUES
- """,
- old_events + older_unrequested_events + recent_events,
- )
-
- cluster.any_host(insert_events).result()
-
- 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"))
+ thirteen, eighteen, no_retention = _teams_with_13_and_18_months()
+ _insert_events(
+ cluster,
+ _events(thirteen.id, _mid_month(15), 0, 3)
+ + _events(thirteen.id, _mid_month(20), 100, 4)
+ + _events(thirteen.id, _first_hour_of_month(13), 200, 5)
+ + _events(eighteen.id, _mid_month(15), 0, 6)
+ + _events(eighteen.id, _mid_month(20), 100, 7)
+ + _events(eighteen.id, _first_hour_of_month(18), 200, 8)
+ + _events(no_retention.id, _mid_month(20), 0, 9),
+ )
- def count_events_by_partition(client: Client) -> dict[int, int]:
- rows = client.execute(
- f"""
- SELECT toYYYYMM(timestamp), count(*)
- FROM writable_events
- WHERE team_id IN ({", ".join(str(t) for t in team_ids)})
- GROUP BY toYYYYMM(timestamp)
- """
- )
- return dict(rows)
+ monthly_old_events_cleanup_job.execute_in_process(resources={"cluster": cluster})
- 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),
+ assert _count_by_team_and_partition(cluster, [thirteen.id, eighteen.id, no_retention.id]) == {
+ (thirteen.id, _partition(_first_hour_of_month(13))): 5,
+ (eighteen.id, _partition(_mid_month(15))): 6,
+ (eighteen.id, _partition(_first_hour_of_month(18))): 8,
+ (no_retention.id, _partition(_mid_month(20))): 9,
}
- monthly_old_events_cleanup_job.execute_in_process(
- run_config={
- "ops": {
- "find_partitions_to_cleanup": {
- "config": {
- "team_ids": team_ids,
- "partitions": [old_partition],
- "min_age_months": 13,
- }
- },
- }
- },
- resources={"cluster": cluster},
- )
-
- assert cluster.any_host(count_events_by_partition).result() == {
- older_unrequested_partition: len(older_unrequested_events),
- recent_partition: len(recent_events),
- }
+@time_machine.travel("2027-01-01", tick=False)
+def test_monthly_old_events_cleanup_schedule_starts_one_run_when_a_retention_is_set():
+ with dagster.build_schedule_context(scheduled_execution_time=datetime(2027, 1, 1, tzinfo=UTC)) as context:
+ assert isinstance(monthly_old_events_cleanup_schedule(context), dagster.SkipReason)
- "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)
+ organization = Organization.objects.create(name="With default")
+ OrganizationEventsRetentionConfig.objects.create(organization=organization, default_events_retention_months=13)
+ Team.objects.create(organization=organization, name="Inherits default")
+ run_request = 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:])
- )
+ assert (run_request.run_key, run_request.run_config) == ("202701", {})
def _insert_pending_deletes(table: PendingDeletesTable, client: Client, count: int = 5, first_id: int = 0) -> None: