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(clickhouse): bound the cohort deletion sweep (#94573)

Eli Reisman3d58fd543547
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.py
index 4a74d9015bb6..17ec2758dc56 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -797,12 +797,21 @@ class MutationWaiters:
waiter.wait(client)
-@dataclass
+class MutationCapacityTimeout(Exception):
+ """Raised when another mutation held the table past a runner's ``capacity_timeout``."""
+
+
+# Mutability is intentional: subclasses set fields in __post_init__ and callers build these
+# incrementally. Stated explicitly so the bare-dataclass ratchet has a declared choice.
+@dataclass(frozen=False)
class MutationRunner(abc.ABC):
table: str
parameters: Mapping[str, Any] = field(default_factory=dict, kw_only=True)
settings: Mapping[str, Any] = field(default_factory=dict, kw_only=True)
force: bool = field(default=False, kw_only=True) # whether to force the mutation to run even if it already exists
+ # How long to wait for the table to be free of other mutations before giving up. 0 waits
+ # forever, which is what a caller with no deadline of its own wants.
+ capacity_timeout: float = field(default=0.0, kw_only=True)
@abc.abstractmethod
def get_all_commands(self) -> Set[str]:
@@ -868,7 +877,12 @@ class MutationRunner(abc.ABC):
Block until the target table has no unfinished mutations before enqueueing a new one, since tables can be
configured with ``number_of_mutations_to_throw`` to reject new mutations while others (e.g. a long-running
backfill) are still in flight.
+
+ This runs before the mutation exists, so a caller's own wait-for-completion deadline cannot cover it. A
+ mutation nobody here started can hold the table indefinitely, so ``capacity_timeout`` is what stops that
+ from holding the caller open forever.
"""
+ deadline = time.monotonic() + self.capacity_timeout if self.capacity_timeout else None
while True:
[[count]] = client.execute(
"""
@@ -880,6 +894,11 @@ class MutationRunner(abc.ABC):
)
if count == 0:
return
+ if deadline is not None and time.monotonic() > deadline:
+ raise MutationCapacityTimeout(
+ f"{self.table} still has {count} unfinished mutation(s)"
+ f" after {self.capacity_timeout:.0f}s waiting for capacity"
+ )
logger.info(
"Waiting for %s unfinished mutation(s) on %s before enqueueing new mutation (checking again in %ss)...",
count,
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index 939fce63aaba..c5fb68c855ce 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -18,6 +18,7 @@ from posthog.clickhouse.cluster import (
ClickhouseCluster,
HostInfo,
LightweightDeleteMutationRunner,
+ MutationCapacityTimeout,
MutationNotFound,
MutationWaiter,
Query,
@@ -888,3 +889,50 @@ def test_query_repr_keeps_short_query_intact():
rendered = repr(Query("SELECT 1"))
assert "truncated" not in rendered
assert "SELECT 1" in rendered
+
+
+def _client_reporting_unfinished(counts: list[int]) -> Mock:
+ remaining = list(counts)
+ client = Mock(spec=Client)
+ client.execute.side_effect = lambda *args, **kwargs: [[remaining.pop(0) if len(remaining) > 1 else remaining[0]]]
+ return client
+
+
+def test_wait_for_mutation_capacity_returns_once_the_table_is_free() -> None:
+ runner = LightweightDeleteMutationRunner(table="person", predicate="1")
+ client = _client_reporting_unfinished([2, 1, 0])
+
+ with patch("posthog.clickhouse.cluster.time.sleep"):
+ runner.wait_for_mutation_capacity(client, poll_interval=0)
+
+ assert client.execute.call_count == 3
+
+
+def test_wait_for_mutation_capacity_waits_indefinitely_by_default() -> None:
+ # The default has to stay "wait forever": every caller that predates capacity_timeout relies on
+ # it, and a deadline appearing under them would fail runs that today merely wait.
+ runner = LightweightDeleteMutationRunner(table="person", predicate="1")
+ assert runner.capacity_timeout == 0.0
+
+ client = _client_reporting_unfinished([1] * 5 + [0])
+ with (
+ patch("posthog.clickhouse.cluster.time.sleep"),
+ patch("posthog.clickhouse.cluster.time.monotonic", side_effect=range(1_000_000, 1_000_100)),
+ ):
+ runner.wait_for_mutation_capacity(client, poll_interval=0)
+
+ assert client.execute.call_count == 6
+
+
+def test_wait_for_mutation_capacity_gives_up_once_capacity_timeout_passes() -> None:
+ # This wait happens before the mutation exists, so the caller's wait-for-completion deadline
+ # cannot cover it; without this bound a mutation nobody here started blocks the run forever.
+ runner = LightweightDeleteMutationRunner(table="person", predicate="1", capacity_timeout=30.0)
+ client = _client_reporting_unfinished([1])
+
+ with (
+ patch("posthog.clickhouse.cluster.time.sleep"),
+ patch("posthog.clickhouse.cluster.time.monotonic", side_effect=[0.0, 10.0, 31.0]),
+ ):
+ with pytest.raises(MutationCapacityTimeout, match="waiting for capacity"):
+ runner.wait_for_mutation_capacity(client, poll_interval=0)
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.py
index b25f4992108d..dfb27be01a73 100644
--- a/posthog/dags/clickhouse_cleanup.py
+++ b/posthog/dags/clickhouse_cleanup.py
@@ -77,6 +77,12 @@ PERSIST_PAGE_SIZE = 50_000
# raise team_batches together with max_persons when draining a large backlog in checkpoints.
DEFAULT_TEAM_BATCHES = 1
+# How many cohorts one run sweeps per deletion type. Bounded rather than unlimited because a
+# sensor can start this run unattended. One delete chunk covers 500 cohorts and was measured on
+# prod-EU reading 0.63% of `cohortpeople`, so this is a few chunks of work per run, and a capped
+# run leaves the rest queued.
+DEFAULT_MAX_COHORTS = 2_000
+
class CleanupConfig(dagster.Config):
"""Read once, by the first op, and carried to every later op on CleanupRun.
@@ -108,11 +114,26 @@ class CleanupConfig(dagster.Config):
default=1800,
description="Fail a delete batch when attempts keep failing and no part completes for this many seconds.",
)
+ mutation_capacity_timeout: int = pydantic.Field(
+ default=3600,
+ description="Fail a delete batch that cannot be enqueued because another mutation has held the table for "
+ "this many seconds. This wait happens before the mutation exists, so mutation_wait_deadline cannot cover it.",
+ )
mutation_wait_deadline: int = pydantic.Field(
default=86400,
description="Fail a delete batch that has not finished after this many seconds, even when it is healthy. "
"A mutation blocked behind another table-sized mutation would otherwise hold the run open forever.",
)
+ cohort_sweep: bool = pydantic.Field(
+ default=True,
+ description="Run the cohort membership sweep. False skips it and goes straight to the person sweep, "
+ "which is the lever to pull if cohort mutations misbehave.",
+ )
+ max_cohorts: int = pydantic.Field(
+ default=DEFAULT_MAX_COHORTS,
+ description="Sweep at most this many cohorts per deletion type, 0 for all of them. A capped run "
+ "leaves the rest queued for the next one. Bounded by default because this job can run unattended.",
+ )
max_persons: int = pydantic.Field(
default=0,
description="Snapshot at most this many deleted persons, 0 for all of them. A capped run deletes a slice "
@@ -162,27 +183,31 @@ class SnapshotTable:
"""
return f"SELECT {self.keys} FROM {self.qualified_name} WHERE run_id = '{self.run_id}'"
- def count(self, client: Client) -> int:
+ def count(self, client: Client, settings: Mapping[str, int] | None = None) -> int:
[[count]] = client.execute(
f"SELECT count() FROM {self.qualified_name} WHERE run_id = %(run_id)s",
{"run_id": self.run_id},
+ settings=settings,
)
return count
- def team_ids(self, client: Client) -> list[int]:
+ def team_ids(self, client: Client, settings: Mapping[str, int] | None = None) -> list[int]:
rows = client.execute(
f"SELECT DISTINCT team_id FROM {self.qualified_name} WHERE run_id = %(run_id)s ORDER BY team_id",
{"run_id": self.run_id},
+ settings=settings,
)
return [row[0] for row in rows]
- def distinct_key_count(self, client: Client) -> int:
+ def distinct_key_count(self, client: Client, settings: Mapping[str, int] | None = None) -> int:
# Deduplicated, so the number is stable whether or not a merge has collapsed the
- # duplicate rows a retried populate leaves behind.
+ # duplicate rows a retried populate leaves behind. Grouping a run's whole worklist is the
+ # heaviest read outside the populates, so it takes the same caps they do.
[[count]] = client.execute(
f"SELECT count() FROM (SELECT {self.keys} FROM {self.qualified_name}"
f" WHERE run_id = %(run_id)s GROUP BY {self.keys})",
{"run_id": self.run_id},
+ settings=settings,
)
return count
@@ -440,11 +465,14 @@ class CleanupRun:
dry_run: bool
cleanup: bool
team_batches: int
+ cohort_sweep: bool
+ max_cohorts: int
shards: int
max_execution_time: int
max_memory_usage: int
dictionary_load_timeout: int
mutation_stall_timeout: int
+ mutation_capacity_timeout: int
mutation_wait_deadline: int
max_persons: int
min_team_id: int
@@ -467,11 +495,14 @@ class CleanupRun:
dry_run=config.dry_run,
cleanup=config.cleanup,
team_batches=config.team_batches,
+ cohort_sweep=config.cohort_sweep,
+ max_cohorts=config.max_cohorts,
shards=config.shards,
max_execution_time=config.max_execution_time,
max_memory_usage=config.max_memory_usage,
dictionary_load_timeout=config.dictionary_load_timeout,
mutation_stall_timeout=config.mutation_stall_timeout,
+ mutation_capacity_timeout=config.mutation_capacity_timeout,
mutation_wait_deadline=config.mutation_wait_deadline,
max_persons=config.max_persons,
min_team_id=config.min_team_id,
@@ -548,12 +579,36 @@ def clear_removed_cohort_data(
context.log.info("dry run: skipping the cohort sweep")
return run
- failed = sweep_cohort_deletions()
- context.add_output_metadata({"failed_passes": dagster.MetadataValue.text(", ".join(failed) or "none")})
+ if not run.cohort_sweep:
+ context.log.warning("cohort sweep disabled, going straight to the person sweep")
+ return run
+
+ # The query tags are what let `system.query_log` tell this run's cohort mutations apart from
+ # any other traffic afterwards, which is how the sweep gets tuned.
+ report = sweep_cohort_deletions(max_cohorts=run.max_cohorts, delete_settings=settings_with_log_comment(context))
+ context.add_output_metadata(
+ {
+ "cohorts_targeted": dagster.MetadataValue.int(report.targets),
+ "cohorts_already_clear": dagster.MetadataValue.int(report.cleared),
+ "deletions_marked_verified": dagster.MetadataValue.int(report.marked),
+ "cohort_mutations": dagster.MetadataValue.int(report.mutations),
+ "unparseable_keys": dagster.MetadataValue.int(report.unparseable_keys),
+ "mark_seconds": dagster.MetadataValue.float(report.mark_seconds),
+ "delete_seconds": dagster.MetadataValue.float(report.delete_seconds),
+ "drain_seconds": dagster.MetadataValue.float(report.drain_seconds),
+ "failed_passes": dagster.MetadataValue.text(", ".join(report.failed) or "none"),
+ }
+ )
+ # Op metadata dies with the run's history; these survive it, and are what a later tuning pass
+ # reads once system.part_log has rolled over.
+ metrics = MetricsClient(cluster)
+ _emit(metrics, "clickhouse_cleanup_cohorts_swept", {}, value=report.targets)
+ _emit(metrics, "clickhouse_cleanup_cohort_mutations", {}, value=report.mutations)
+ _emit(metrics, "clickhouse_cleanup_cohort_deletions_marked", {}, value=report.marked)
# The prometheus counters sweep_cohort_deletions increments die with this run's pod, so the
# scrapeable record of a failed pass is the ClickHouse-backed counter.
- for name in failed:
- _emit(MetricsClient(cluster), "clickhouse_cleanup_cohort_sweep_failed_passes", {"pass": name})
+ for name in report.failed:
+ _emit(metrics, "clickhouse_cleanup_cohort_sweep_failed_passes", {"pass": name})
return run
@@ -578,7 +633,9 @@ def snapshot_deleted_persons(
# The insert lands on one host, but every host reads this table when the dictionary loads.
cluster.map_all_hosts(run.persons.sync_replica).result()
- count = cluster.any_host_by_role(run.persons.distinct_key_count, NodeRole.DATA).result()
+ count = cluster.any_host_by_role(
+ partial(run.persons.distinct_key_count, settings=run.query_settings), NodeRole.DATA
+ ).result()
context.add_output_metadata(
{
"deleted_persons": dagster.MetadataValue.int(count),
@@ -606,7 +663,9 @@ def snapshot_orphaned_distinct_ids(
snapshot_seconds = round(time.monotonic() - started, 1)
_create_dictionary(context, cluster, run.orphaned_dictionary, run)
- count = cluster.any_host_by_role(run.orphaned.distinct_key_count, NodeRole.DATA).result()
+ count = cluster.any_host_by_role(
+ partial(run.orphaned.distinct_key_count, settings=run.query_settings), NodeRole.DATA
+ ).result()
context.add_output_metadata(
{
"orphaned_distinct_ids": dagster.MetadataValue.int(count),
@@ -632,14 +691,18 @@ def recheck_revived_persons(name: str) -> dagster.OpDefinition:
cluster: dagster.ResourceParam[ClickhouseCluster],
run: CleanupRun,
) -> CleanupRun:
- persons_before = cluster.any_host_by_role(run.revived.count, NodeRole.DATA).result()
+ persons_before = cluster.any_host_by_role(
+ partial(run.revived.count, settings=run.query_settings), NodeRole.DATA
+ ).result()
persons_total = cluster.any_host_by_role(
partial(run.revived.populate, persons=run.persons, settings=run.query_settings), NodeRole.DATA
).result()
cluster.map_all_hosts(run.revived.sync_replica).result()
# Runs second: which distinct ids still qualify depends on which persons are still deleted.
- ids_before = cluster.any_host_by_role(run.revived_distinct_ids.count, NodeRole.DATA).result()
+ ids_before = cluster.any_host_by_role(
+ partial(run.revived_distinct_ids.count, settings=run.query_settings), NodeRole.DATA
+ ).result()
ids_total = cluster.any_host_by_role(
partial(
run.revived_distinct_ids.populate,
@@ -861,6 +924,16 @@ def _wait_for_mutation(
time.sleep(MUTATION_POLL_SECONDS)
+@frozen
+class OrderedDeleteReport:
+ """What one table's ordered delete cost. The wait deadlines are set from this distribution,
+ so it is recorded as op metadata rather than left in the run's logs."""
+
+ batches: int
+ seconds_total: float
+ seconds_max: float
+
+
@dataclass(frozen=True, kw_only=True)
class TeamRange:
"""One inclusive [low, high] slice of the candidate team ids."""
@@ -896,8 +969,9 @@ def _run_ordered_delete(
team_ranges: list[TeamRange],
metrics: MetricsClient,
stall_timeout: float,
+ capacity_timeout: float,
wait_deadline: float,
-) -> int:
+) -> "OrderedDeleteReport":
"""Delete every snapshotted row from `table`, oldest version first.
Two passes per team range, in this order and never merged:
@@ -922,13 +996,16 @@ def _run_ordered_delete(
)
batches = 0
+ durations: list[float] = []
for team_range in team_ranges:
for pass_name, key_predicate in passes:
+ started = time.monotonic()
predicate = f"team_id >= {team_range.low} AND team_id <= {team_range.high} AND {key_predicate}"
runner = LightweightDeleteMutationRunner(
table=table,
predicate=predicate,
settings=settings_with_log_comment(context),
+ capacity_timeout=capacity_timeout,
)
# Both tables are replicated and not sharded, so a mutation started on one host
# reaches all of them.
@@ -942,21 +1019,38 @@ def _run_ordered_delete(
stall_timeout,
wait_deadline,
)
+ durations.append(time.monotonic() - started)
_emit(metrics, "clickhouse_cleanup_delete_pass_total", {"table": table, "pass": pass_name})
batches += 1
context.log.info("%s: completed %s ordered delete mutations", table, batches)
- return batches
+ # sum() of an empty list is an int, and dagster's float metadata rejects one.
+ return OrderedDeleteReport(
+ batches=batches,
+ seconds_total=round(sum(durations, 0.0), 1),
+ seconds_max=round(max(durations, default=0.0), 1),
+ )
-def _require_snapshot_intact(cluster: ClickhouseCluster, table: SnapshotTable, recorded: int) -> None:
+def _delete_metadata(ranges: list[TeamRange], report: "OrderedDeleteReport") -> dict[str, dagster.MetadataValue]:
+ return {
+ "team_ranges": dagster.MetadataValue.int(len(ranges)),
+ "mutation_batches": dagster.MetadataValue.int(report.batches),
+ "mutation_seconds_total": dagster.MetadataValue.float(report.seconds_total),
+ "mutation_seconds_max": dagster.MetadataValue.float(report.seconds_max),
+ }
+
+
+def _require_snapshot_intact(
+ cluster: ClickhouseCluster, table: SnapshotTable, recorded: int, settings: Mapping[str, int]
+) -> None:
"""Fail the run if the snapshot lost rows since it was recorded.
The 14-day TTL drops a run's partition unconditionally, so a run stalled past it would
otherwise sweep from a silently shrunken worklist, and nothing would distinguish
"under-deleted" from "had fewer rows".
"""
- current = cluster.any_host_by_role(table.distinct_key_count, NodeRole.DATA).result()
+ current = cluster.any_host_by_role(partial(table.distinct_key_count, settings=settings), NodeRole.DATA).result()
if current != recorded:
raise dagster.Failure(
f"{table.table_name} holds {current} keys for this run but {recorded} were snapshotted;"
@@ -975,11 +1069,11 @@ def delete_orphaned_distinct_ids(
context.log.info("dry run: skipping the delete from %s", PERSON_DISTINCT_ID2_TABLE)
return run
- _require_snapshot_intact(cluster, run.orphaned, run.orphaned_count)
- ranges = _team_ranges(cluster.any_host_by_role(run.orphaned.team_ids, NodeRole.DATA).result(), run.team_batches)
- context.add_output_metadata({"team_ranges": dagster.MetadataValue.int(len(ranges))})
+ _require_snapshot_intact(cluster, run.orphaned, run.orphaned_count, run.query_settings)
+ team_ids = cluster.any_host_by_role(partial(run.orphaned.team_ids, settings=run.query_settings), NodeRole.DATA)
+ ranges = _team_ranges(team_ids.result(), run.team_batches)
- _run_ordered_delete(
+ report = _run_ordered_delete(
context,
cluster,
PERSON_DISTINCT_ID2_TABLE,
@@ -988,8 +1082,10 @@ def delete_orphaned_distinct_ids(
ranges,
MetricsClient(cluster),
run.mutation_stall_timeout,
+ run.mutation_capacity_timeout,
run.mutation_wait_deadline,
)
+ context.add_output_metadata(_delete_metadata(ranges, report))
return replace(run, distinct_ids_deleted_at=datetime.now(UTC))
@@ -1108,11 +1204,11 @@ def delete_persons(
context.log.info("dry run: skipping the delete from %s", PERSONS_TABLE)
return run
- _require_snapshot_intact(cluster, run.persons, run.persons_count)
- ranges = _team_ranges(cluster.any_host_by_role(run.persons.team_ids, NodeRole.DATA).result(), run.team_batches)
- context.add_output_metadata({"team_ranges": dagster.MetadataValue.int(len(ranges))})
+ _require_snapshot_intact(cluster, run.persons, run.persons_count, run.query_settings)
+ team_ids = cluster.any_host_by_role(partial(run.persons.team_ids, settings=run.query_settings), NodeRole.DATA)
+ ranges = _team_ranges(team_ids.result(), run.team_batches)
- _run_ordered_delete(
+ report = _run_ordered_delete(
context,
cluster,
PERSONS_TABLE,
@@ -1121,8 +1217,10 @@ def delete_persons(
ranges,
MetricsClient(cluster),
run.mutation_stall_timeout,
+ run.mutation_capacity_timeout,
run.mutation_wait_deadline,
)
+ context.add_output_metadata(_delete_metadata(ranges, report))
return run
diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.py
index a0b390154403..db86a612547f 100644
--- a/posthog/dags/tests/test_clickhouse_cleanup.py
+++ b/posthog/dags/tests/test_clickhouse_cleanup.py
@@ -675,13 +675,30 @@ def test_clears_cohort_rows_and_marks_the_deletion_verified_on_the_next_run(
assert AsyncDeletion.objects.get(team_id=TEAM_ID).delete_verified_at is not None
+def test_cohort_sweep_can_be_switched_off_without_stopping_the_person_sweep(
+ cluster: ClickhouseCluster, persons_database
+):
+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ seed_cohort_rows(cluster, count=10)
+ AsyncDeletion.objects.create(deletion_type=DeletionType.Cohort_full, team_id=TEAM_ID, key=f"{COHORT_ID}_0")
+
+ # The lever to pull if cohort mutations misbehave mid-rollout: the person half still runs.
+ switched_off = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False, "cohort_sweep": False}}}}
+ result = run_job(cluster, persons_database, run_config=switched_off)
+
+ assert result.success
+ assert cluster.any_host(cohort_rows).result() == 10
+ assert AsyncDeletion.objects.get(team_id=TEAM_ID).delete_verified_at is None
+
+
@pytest.mark.django_db
def test_cohort_delete_pass_runs_when_the_mark_pass_fails(cluster: ClickhouseCluster, persons_database):
seed_cohort_rows(cluster, count=10)
AsyncDeletion.objects.create(deletion_type=DeletionType.Cohort_full, team_id=TEAM_ID, key=f"{COHORT_ID}_0")
with patch(
- "posthog.models.async_deletion.delete_cohorts.AsyncCohortDeletion.mark_deletions_done",
+ "posthog.models.async_deletion.delete_cohorts._mark_verified",
side_effect=Exception("boom"),
):
result = run_job(cluster, persons_database)
diff --git a/posthog/management/commands/start_delete_mutation.py b/posthog/management/commands/start_delete_mutation.py
index 1d69d9a80c25..b131bcd943bb 100644
--- a/posthog/management/commands/start_delete_mutation.py
+++ b/posthog/management/commands/start_delete_mutation.py
@@ -22,5 +22,11 @@ class Command(BaseCommand):
def run():
logger.info("Starting deletion of data for teams")
- failed = sweep_cohort_deletions()
- logger.info("Finished deletion of data for teams", failed_passes=failed)
+ report = sweep_cohort_deletions()
+ logger.info(
+ "Finished deletion of data for teams",
+ cohorts=report.targets,
+ mutations=report.mutations,
+ marked=report.marked,
+ failed_passes=report.failed,
+ )
diff --git a/posthog/models/async_deletion/delete_cohorts.py b/posthog/models/async_deletion/delete_cohorts.py
index ad77f6ef431d..40403e12076a 100644
--- a/posthog/models/async_deletion/delete_cohorts.py
+++ b/posthog/models/async_deletion/delete_cohorts.py
@@ -1,11 +1,41 @@
+"""Sweep `cohortpeople` rows for cohorts that were deleted, or recalculated past a version.
+
+A queued deletion is bookkeeping, not a unit of work. `posthog/api/cohort.py` writes one
+`AsyncDeletion` per team that can see a cohort, so one deleted cohort can queue thousands of rows
+that all name the same `(team_id, cohort_id)`. Working from the rows directly means holding every
+one of them in memory and issuing a table-sized mutation per 500 of them, neither of which is
+bounded by anything the cohort data itself controls.
+
+So the sweep collapses the queue into targets first. Every queued deletion for one
+`(team_id, cohort_id)` becomes a single target, because the ORed predicates it would otherwise
+produce reduce to one:
+
+ (version < V1) OR (version < V2) OR ... == version < max(Vi)
+
+The collapse is exact rather than approximate, and it is what bounds the sweep: memory and
+mutation count follow the number of distinct cohorts, which the queue cannot inflate.
+"""
+
+import time
+from collections.abc import Mapping
+from dataclasses import replace
+from datetime import datetime
from typing import Any
+from django.conf import settings
+from django.db.models import BigIntegerField, Func, Max, QuerySet, TextField, Value
+from django.db.models.functions import Cast
+from django.utils import timezone
+
+import structlog
from more_itertools import chunked
from prometheus_client import Counter
from posthog.clickhouse.client import sync_execute
+from posthog.dataclasses import frozen
from posthog.models.async_deletion import AsyncDeletion, DeletionType
-from posthog.models.async_deletion.delete import AsyncDeletionProcess, logger
+
+logger = structlog.get_logger(__name__)
COHORT_DELETION_MARK_FAILURE_COUNTER = Counter(
"posthog_cohort_deletion_mark_failure_total",
@@ -17,121 +47,430 @@ COHORT_DELETION_RUN_FAILURE_COUNTER = Counter(
"Times cohort deletion run failed",
)
+COHORT_DELETION_UNPARSEABLE_KEY_COUNTER = Counter(
+ "posthog_cohort_deletion_unparseable_keys_total",
+ "Queued cohort deletions whose key does not name a cohort, and so were skipped",
+ ["deletion_type"],
+)
-# A backlog of pending deletions would otherwise become one mutation whose predicate ORs every
-# cohort together. Chunking keeps each mutation's predicate and blast radius bounded, and a chunk
-# that fails leaves the later chunks for the next run.
+# How many targets one mutation's predicate ORs together. Each target contributes an indexed
+# `(team_id, cohort_id)` range, so this bounds predicate size, not the rows a mutation reads.
COHORT_DELETION_CHUNK_SIZE = 500
+# How many queued rows one page of the marking pass holds. Bounds both the rows a single
+# transaction rewrites and the memory the page occupies.
+COHORT_MARK_PAGE_SIZE = 50_000
-class AsyncCohortDeletion(AsyncDeletionProcess):
- DELETION_TYPES = [DeletionType.Cohort_full, DeletionType.Cohort_stale]
+# Unfinished mutations on `cohortpeople` the sweep will tolerate before it stops enqueueing more.
+# Mutations are enqueued asynchronously, so without this every target chunk lands at once and they
+# all compete for the same background pool.
+COHORT_MUTATION_CAPACITY = 2
+COHORT_MUTATION_POLL_SECONDS = 30.0
+# Log one line in this many polls. Dagster stores every log line, and a drain can poll for an hour,
+# so the wait reports periodically rather than every tick.
+COHORT_POLL_LOG_EVERY = 10
+# A mutation the sweep did not enqueue can hold the table indefinitely, so waiting for it needs its
+# own bound; the sweep fails rather than blocking the run forever.
+COHORT_MUTATION_TIMEOUT_SECONDS = 3600.0
- def process(self, deletions: list[AsyncDeletion]):
- if len(deletions) == 0:
- logger.warn("No AsyncDeletion for cohorts to perform")
- return
- logger.warn(
- "Starting AsyncDeletion on `cohortpeople` table in ClickHouse",
- {
- "count": len(deletions),
- "team_ids": list({row.team_id for row in deletions}),
- },
- )
+# nosemgrep: python.django.security.audit.extends-custom-expression.extends-custom-expression
+class KeyPart(Func):
+ """Postgres `substring(text from pattern)`, returning the first capture group or NULL.
- for chunk in chunked(deletions, COHORT_DELETION_CHUNK_SIZE):
- conditions, args = self._conditions(chunk)
-
- # nosemgrep: clickhouse-fstring-param-audit - conditions from internal _conditions method
- sync_execute(
- f"""
- DELETE FROM cohortpeople
- WHERE {" OR ".join(conditions)}
- """,
- args,
- settings={},
- )
+ The pattern is always a literal from this module and the only expression is a column, so no
+ caller-supplied text reaches the SQL. Capturing rather than splitting is what makes the cast
+ downstream safe: a key whose version part is the literal "None" yields NULL instead of a value
+ `bigint` cannot parse, so no plan that plays the cast before the filter can fail the query.
+ """
- def _verify_by_group(self, deletion_type: int, async_deletions: list[AsyncDeletion]) -> list[AsyncDeletion]:
- if deletion_type == DeletionType.Cohort_stale or deletion_type == DeletionType.Cohort_full:
- cohort_ids_with_data = self._verify_by_column("team_id, cohort_id", async_deletions)
- return [
- row for row in async_deletions if (row.team_id, int(row.key.split("_")[0])) not in cohort_ids_with_data
- ]
- else:
- return []
-
- def _verify_by_column(self, distinct_columns: str, async_deletions: list[AsyncDeletion]) -> set[tuple[Any, ...]]:
- found: set[tuple[Any, ...]] = set()
- for chunk in chunked(async_deletions, COHORT_DELETION_CHUNK_SIZE):
- conditions, args = self._conditions(chunk)
- # nosemgrep: clickhouse-fstring-param-audit - distinct_columns hardcoded, conditions internal
- clickhouse_result = sync_execute(
- f"""
- SELECT DISTINCT {distinct_columns}
- FROM cohortpeople
- WHERE {" OR ".join(conditions)}
- """,
- args,
- settings={},
- )
- found.update(tuple(row) for row in clickhouse_result)
- return found
+ function = "substring"
+ arity = 2
+ template = "%(function)s(%(expressions)s)"
+ arg_joiner = " from "
+ output_field = TextField()
+
+
+@frozen
+class CohortKey:
+ """The cohort a queued deletion names."""
+
+ team_id: int
+ cohort_id: int
+
+
+@frozen
+class CohortSweepReport:
+ """What one sweep did, for the op to record. Aggregated across both deletion types.
+
+ Phase seconds separate the three costs a run trades off: reading the queue to tick off
+ finished cohorts, issuing the mutations, and waiting for the cluster to apply them. Tuning
+ `max_cohorts` needs them apart, and an op-level duration cannot take them apart.
+ """
+
+ targets: int
+ cleared: int
+ marked: int
+ mutations: int
+ unparseable_keys: int
+ mark_seconds: float
+ delete_seconds: float
+ drain_seconds: float
+ failed: tuple[str, ...]
+
+
+@frozen
+class MarkOutcome:
+ """What one marking pass ticked off, and what it could not read."""
+
+ marked: int
+ unparseable_keys: int
+
+
+@frozen
+class MutationCounts:
+ """How many `cohortpeople` mutations are in view, and how many of those are unfinished."""
+
+ seen: int
+ unfinished: int
+
+
+@frozen
+class CohortDeleteTarget:
+ """One cohort's unit of work, collapsed from every deletion queued against it."""
+
+ team_id: int
+ cohort_id: int
+ # The exclusive version bound, or None to remove every version. `Cohort_full` deletes the whole
+ # cohort; `Cohort_stale` only removes what a later recalculation superseded.
+ below_version: int | None
+
+ @property
+ def key(self) -> CohortKey:
+ return CohortKey(team_id=self.team_id, cohort_id=self.cohort_id)
+
+ @property
+ def condition(self) -> tuple[str, dict[str, Any]]:
+ """The ClickHouse predicate for this target, with its parameters."""
+ suffix = f"{self.team_id}_{self.cohort_id}"
+ params: dict[str, Any] = {f"team_id_{suffix}": self.team_id, f"cohort_id_{suffix}": self.cohort_id}
+ clause = f"( team_id = %(team_id_{suffix})s AND cohort_id = %(cohort_id_{suffix})s"
+ if self.below_version is not None:
+ params[f"version_{suffix}"] = self.below_version
+ clause += f" AND version < %(version_{suffix})s"
+ return clause + " )", params
+
+
+def _conditions(targets: list[CohortDeleteTarget]) -> tuple[list[str], dict[str, Any]]:
+ clauses, params = [], {}
+ for target in targets:
+ clause, target_params = target.condition
+ clauses.append(clause)
+ params.update(target_params)
+ return clauses, params
+
+
+def _cohort_id(key: str) -> int | None:
+ """The cohort id a queued deletion's key names, or None when it names nothing.
+
+ Keys are written as `<cohort_id>_<version>` and, for a team that is not the cohort's own,
+ `<cohort_id>_<version>_<team_id>` (see `posthog/api/cohort.py`). `version` is also the literal
+ string "None" for a cohort that was never calculated, so the cohort id is the only part that is
+ always a number.
+ """
+ head = key.split("_", 1)[0]
+ return int(head) if head.isdigit() else None
+
+
+def _queued(deletion_type: DeletionType) -> QuerySet[AsyncDeletion]:
+ return AsyncDeletion.objects.filter(delete_verified_at__isnull=True, deletion_type=deletion_type)
+
+
+def _collapse(deletion_type: DeletionType, limit: int = 0) -> list[CohortDeleteTarget]:
+ """Reduce the queued deletions of one type to one target per cohort.
+
+ The aggregation, the ordering and the cap all run in the database, so what comes back is bounded
+ by `limit`, or by the number of distinct cohorts, rather than by the queue depth. A key that
+ names no cohort is filtered out here and counted by the marking pass.
+ """
+ parseable = _queued(deletion_type).filter(key__regex=r"^\d+_")
+ cohort_id = Cast(KeyPart("key", Value(r"^(\d+)_")), BigIntegerField())
- def _column_name(self, async_deletion: AsyncDeletion):
- assert async_deletion.deletion_type in (
- DeletionType.Cohort_full,
- DeletionType.Cohort_stale,
+ if deletion_type == DeletionType.Cohort_full:
+ # Every version goes, so there is nothing to collapse beyond the cohort itself.
+ cohorts = (
+ parseable.annotate(cohort_id=cohort_id)
+ .values_list("team_id", "cohort_id")
+ .distinct()
+ .order_by("team_id", "cohort_id")
)
- return "cohort_id"
-
- def _condition(self, async_deletion: AsyncDeletion, suffix: str) -> tuple[str, dict]:
- team_id_param = f"team_id{suffix}"
- key_param = f"key{suffix}"
- version_param = f"version{suffix}"
- if async_deletion.deletion_type == DeletionType.Cohort_full:
- key, _ = async_deletion.key.split("_")
- return (
- f"( team_id = %({team_id_param})s AND {self._column_name(async_deletion)} = %({key_param})s )",
- {
- team_id_param: async_deletion.team_id,
- key_param: key,
- },
+ return [
+ CohortDeleteTarget(team_id=t, cohort_id=c, below_version=None)
+ for t, c in (cohorts[:limit] if limit else cohorts)
+ ]
+
+ # Only versioned keys can bound a stale sweep; one without a numeric version names no bound.
+ bounded = (
+ parseable.filter(key__regex=r"^\d+_\d+")
+ .annotate(
+ cohort_id=cohort_id,
+ version=Cast(KeyPart("key", Value(r"^\d+_(\d+)")), BigIntegerField()),
+ )
+ .values("team_id", "cohort_id")
+ .annotate(below_version=Max("version"))
+ .order_by("team_id", "cohort_id")
+ .values_list("team_id", "cohort_id", "below_version")
+ )
+ return [
+ CohortDeleteTarget(team_id=t, cohort_id=c, below_version=v)
+ for t, c, v in (bounded[:limit] if limit else bounded)
+ ]
+
+
+def _server_now() -> datetime:
+ [[now]] = sync_execute("SELECT now()")
+ return now
+
+
+def _mutation_counts(since: datetime | None = None) -> MutationCounts:
+ """Mutations on `cohortpeople`, counting only ones created at or after `since`."""
+ window = "AND create_time >= %(since)s" if since else ""
+ # nosemgrep: clickhouse-fstring-param-audit - window is a literal chosen here, not caller input
+ [[seen, unfinished]] = sync_execute(
+ f"""
+ SELECT count(), countIf(NOT is_done)
+ FROM system.mutations
+ WHERE database = %(database)s AND table = 'cohortpeople' AND NOT is_killed {window}
+ """,
+ {"database": settings.CLICKHOUSE_DATABASE, "since": since},
+ )
+ return MutationCounts(seen=seen, unfinished=unfinished)
+
+
+def _wait_for_capacity(timeout: float = COHORT_MUTATION_TIMEOUT_SECONDS) -> None:
+ """Block until `cohortpeople` is carrying fewer than `COHORT_MUTATION_CAPACITY` mutations.
+
+ Bounded on purpose. A mutation this sweep did not enqueue can hold the table for as long as it
+ likes, and the ClickHouse client is configured with no practical socket timeout, so an unbounded
+ wait here is indistinguishable from a hang.
+ """
+ deadline = time.monotonic() + timeout
+ polls = 0
+ while (unfinished := _mutation_counts().unfinished) >= COHORT_MUTATION_CAPACITY:
+ if time.monotonic() > deadline:
+ raise TimeoutError(f"cohortpeople still has {unfinished} unfinished mutation(s) after {timeout:.0f}s")
+ if polls % COHORT_POLL_LOG_EVERY == 0:
+ logger.info("Waiting for cohortpeople mutation capacity", unfinished=unfinished)
+ polls += 1
+ time.sleep(COHORT_MUTATION_POLL_SECONDS)
+
+
+def _wait_for_drain(issued: int, since: datetime, timeout: float = COHORT_MUTATION_TIMEOUT_SECONDS) -> None:
+ """Block until every mutation this sweep enqueued is visible and finished.
+
+ Waiting on "nothing unfinished" alone is not enough. A mutation entry replicates through
+ Keeper, so for a moment after the ALTER returns the queried host does not know it exists, and a
+ drain that only counts unfinished work reads that gap as success and lets the person sweep
+ start on top of a running mutation.
+ """
+ deadline = time.monotonic() + timeout
+ polls = 0
+ while True:
+ counts = _mutation_counts(since)
+ if counts.seen >= issued and not counts.unfinished:
+ return
+ if time.monotonic() > deadline:
+ raise TimeoutError(
+ f"cohortpeople has {counts.unfinished} unfinished mutation(s)"
+ f" and {counts.seen} of {issued} visible after {timeout:.0f}s"
)
- else:
- key, version = async_deletion.key.split("_")
- return (
- f"( team_id = %({team_id_param})s AND {self._column_name(async_deletion)} = %({key_param})s AND version < %({version_param})s )",
- {
- team_id_param: async_deletion.team_id,
- version_param: version,
- key_param: key,
- },
+ if polls % COHORT_POLL_LOG_EVERY == 0:
+ logger.info(
+ "Waiting for cohortpeople mutations to drain",
+ seen=counts.seen,
+ issued=issued,
+ unfinished=counts.unfinished,
)
+ polls += 1
+ time.sleep(COHORT_MUTATION_POLL_SECONDS)
+
+
+def _delete(targets: list[CohortDeleteTarget], settings: Mapping[str, Any] | None = None) -> int:
+ """Remove the cohort rows each target names, one mutation per chunk. Returns mutations issued.
+
+ `lightweight_deletes_sync` is set here rather than left to the server, which defaults it to
+ "wait for every replica". That default would block each chunk inside the client for as long as
+ the mutation takes, with no bound and no progress reporting. Enqueueing asynchronously and
+ pacing on `system.mutations` instead keeps the concurrency explicit and every wait bounded.
+
+ `settings` carries the caller's query tags. Without them these mutations cannot be told apart
+ from any other traffic in `system.query_log`, and a run cannot be measured after the fact.
+ """
+ issued = 0
+ for chunk in chunked(targets, COHORT_DELETION_CHUNK_SIZE):
+ _wait_for_capacity()
+ conditions, params = _conditions(list(chunk))
+ # nosemgrep: clickhouse-fstring-param-audit - conditions come from CohortDeleteTarget.condition
+ sync_execute(
+ f"""
+ DELETE FROM cohortpeople
+ WHERE {" OR ".join(conditions)}
+ """,
+ params,
+ settings={**(settings or {}), "lightweight_deletes_sync": 0},
+ )
+ issued += 1
+ return issued
+
+def _cleared(targets: list[CohortDeleteTarget]) -> set[CohortKey]:
+ """The targets whose rows are already gone from `cohortpeople`.
-def sweep_cohort_deletions() -> list[str]:
- """Run both cohort deletion passes and return the names of any that failed.
+ A deletion bounded at version V still has rows if and only if some row sits below V, which is
+ true if and only if the cohort's lowest surviving version is below V. A cohort with no rows at
+ all never appears in the lookup, so it clears whatever its bound.
- Each pass is guarded on its own: failing to tick off cohorts whose rows are already gone
- must not stop the pass that actually removes rows.
+ `sign` is deliberately not filtered. A membership the reader treats as removed (`sign = -1`)
+ is still a row the sweep has to delete, and counting it here can only hold a cohort back for
+ another run, never clear one whose rows are still present.
"""
- runner = AsyncCohortDeletion()
- failed = []
-
- try:
- runner.mark_deletions_done()
- except Exception as e:
- logger.error("Failed to mark cohort deletions done", error=e, exc_info=True)
- COHORT_DELETION_MARK_FAILURE_COUNTER.inc()
- failed.append("mark")
-
- try:
- runner.run()
- except Exception as e:
- logger.error("Failed to run cohort deletions", error=e, exc_info=True)
- COHORT_DELETION_RUN_FAILURE_COUNTER.inc()
- failed.append("run")
-
- return failed
+ lowest: dict[CohortKey, int] = {}
+ for chunk in chunked(targets, COHORT_DELETION_CHUNK_SIZE):
+ conditions, params = _conditions([replace(target, below_version=None) for target in chunk])
+ # nosemgrep: clickhouse-fstring-param-audit - conditions come from CohortDeleteTarget.condition
+ rows = sync_execute(
+ f"""
+ SELECT team_id, cohort_id, min(version)
+ FROM cohortpeople
+ WHERE {" OR ".join(conditions)}
+ GROUP BY team_id, cohort_id
+ """,
+ params,
+ settings={},
+ )
+ for team_id, cohort_id, min_version in rows:
+ lowest[CohortKey(team_id=team_id, cohort_id=cohort_id)] = min_version
+
+ return {
+ target.key
+ for target in targets
+ if (surviving := lowest.get(target.key)) is None
+ or (target.below_version is not None and surviving >= target.below_version)
+ }
+
+
+def _mark_verified(deletion_type: DeletionType, cleared: set[CohortKey]) -> MarkOutcome:
+ """Tick off every queued deletion naming a cleared cohort. Returns how many rows were marked.
+
+ Paged on the primary key rather than filtered on the cohort id. The cohort id lives inside
+ `key`, and no index covers a prefix match on it under this database's collation, so a predicate
+ shaped that way plans as a sequential scan and pays for the whole queue once per statement.
+ Walking the primary key reads the queue once in total, and each update addresses rows by id.
+ """
+ if not cleared:
+ return MarkOutcome(marked=0, unparseable_keys=0)
+
+ now = timezone.now()
+ marked = 0
+ unparseable = 0
+ after = 0
+ while True:
+ page = list(
+ _queued(deletion_type)
+ .filter(pk__gt=after)
+ .order_by("pk")
+ .values_list("id", "team_id", "key")[:COHORT_MARK_PAGE_SIZE]
+ )
+ if not page:
+ break
+ after = page[-1][0]
+
+ ids = []
+ for row_id, team_id, key in page:
+ cohort_id = _cohort_id(key)
+ if cohort_id is None:
+ unparseable += 1
+ elif CohortKey(team_id=team_id, cohort_id=cohort_id) in cleared:
+ ids.append(row_id)
+ if ids:
+ marked += AsyncDeletion.objects.filter(pk__in=ids).update(delete_verified_at=now)
+ if len(page) < COHORT_MARK_PAGE_SIZE:
+ break
+
+ if unparseable:
+ # Not fatal: a key the producer never wrote cannot match cohort rows either, so skipping it
+ # loses no deletion. Counted because it means the key format has drifted.
+ COHORT_DELETION_UNPARSEABLE_KEY_COUNTER.labels(deletion_type=deletion_type.name).inc(unparseable)
+ logger.warning("Skipped cohort deletions with unparseable keys", count=unparseable, deletion_type=deletion_type)
+
+ return MarkOutcome(marked=marked, unparseable_keys=unparseable)
+
+
+def sweep_cohort_deletions(max_cohorts: int = 0, delete_settings: Mapping[str, Any] | None = None) -> CohortSweepReport:
+ """Tick off cohorts whose rows are already gone, then remove the rows still queued.
+
+ `max_cohorts` caps how many cohorts one run takes on, per deletion type, 0 for all of them.
+ Whatever it excludes stays queued for the next run. `delete_settings` tags the mutations so a
+ run can be measured in `system.query_log` afterwards.
+
+ Marking runs first, and reports on what earlier runs removed. Mutations are enqueued
+ asynchronously, so the rows this run deletes are still readable when it finishes; a marking pass
+ placed after the delete would find them and tick off nothing, every run, forever.
+
+ Each pass is guarded on its own: failing to tick off cohorts whose rows are already gone must
+ not stop the pass that removes rows.
+ """
+ failed: list[str] = []
+ targets_seen = cleared_seen = marked = unparseable = issued = 0
+ mark_seconds = delete_seconds = 0.0
+ started_at = _server_now()
+
+ for deletion_type in (DeletionType.Cohort_full, DeletionType.Cohort_stale):
+ targets = _collapse(deletion_type, limit=max_cohorts)
+ if not targets:
+ continue
+ targets_seen += len(targets)
+
+ try:
+ phase = time.monotonic()
+ cleared = _cleared(targets)
+ outcome = _mark_verified(deletion_type, cleared)
+ mark_seconds += time.monotonic() - phase
+ cleared_seen += len(cleared)
+ marked += outcome.marked
+ unparseable += outcome.unparseable_keys
+ # Already gone, so sweeping them again would issue a mutation that removes nothing.
+ targets = [target for target in targets if target.key not in cleared]
+ except Exception:
+ logger.exception("Failed to mark cohort deletions done", deletion_type=deletion_type.name)
+ COHORT_DELETION_MARK_FAILURE_COUNTER.inc()
+ failed.append(f"mark:{deletion_type.name}")
+
+ if not targets:
+ continue
+ try:
+ phase = time.monotonic()
+ issued += _delete(targets, delete_settings)
+ delete_seconds += time.monotonic() - phase
+ except Exception:
+ logger.exception("Failed to run cohort deletions", deletion_type=deletion_type.name)
+ COHORT_DELETION_RUN_FAILURE_COUNTER.inc()
+ failed.append(f"run:{deletion_type.name}")
+
+ # Raised, never recorded as a failed pass. The caller chains the person sweep on this returning,
+ # and the two must not mutate at the same time, so an undrained table has to stop the run rather
+ # than hand back a result that reads as "finished with a warning".
+ drain = time.monotonic()
+ _wait_for_drain(issued, started_at)
+
+ return CohortSweepReport(
+ targets=targets_seen,
+ cleared=cleared_seen,
+ marked=marked,
+ mutations=issued,
+ unparseable_keys=unparseable,
+ mark_seconds=round(mark_seconds, 1),
+ delete_seconds=round(delete_seconds, 1),
+ drain_seconds=round(time.monotonic() - drain, 1),
+ failed=tuple(failed),
+ )
diff --git a/posthog/models/test/__snapshots__/test_async_deletion_model.ambr b/posthog/models/test/__snapshots__/test_async_deletion_model.ambr
index b348652c3814..0241cec5dcab 100644
--- a/posthog/models/test/__snapshots__/test_async_deletion_model.ambr
+++ b/posthog/models/test/__snapshots__/test_async_deletion_model.ambr
@@ -1,16 +1,4 @@
# serializer version: 1
-# name: TestAsyncDeletion.test_delete_cohortpeople
- '''
- SELECT count()
- FROM cohortpeople
- '''
-# ---
-# name: TestAsyncDeletion.test_delete_cohortpeople_version
- '''
- SELECT count()
- FROM cohortpeople
- '''
-# ---
# name: TestAsyncDeletion.test_mark_deletions_done_groups
'''
diff --git a/posthog/models/test/test_async_deletion_model.py b/posthog/models/test/test_async_deletion_model.py
index 12768140aa8a..2ab222a5a722 100644
--- a/posthog/models/test/test_async_deletion_model.py
+++ b/posthog/models/test/test_async_deletion_model.py
@@ -12,7 +12,7 @@ from posthog.test.base import (
from posthog.clickhouse.client import sync_execute
from posthog.models import AsyncDeletion, DeletionType, Team, User
-from posthog.models.async_deletion.delete_cohorts import AsyncCohortDeletion
+from posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions
from posthog.models.async_deletion.delete_events import AsyncEventDeletion
from posthog.models.group.util import create_group
from posthog.models.person.util import create_person, create_person_distinct_id
@@ -435,7 +435,6 @@ class TestAsyncDeletion(ClickhouseTestMixin, ClickhouseDestroyTablesMixin, BaseT
self.assertRowCount(1, "person_static_cohort")
self.assertRowCount(1, "plugin_log_entries")
- @snapshot_clickhouse_queries
def test_delete_cohortpeople(self):
cohort_id = 3
team = self.teams[0]
@@ -447,11 +446,10 @@ class TestAsyncDeletion(ClickhouseTestMixin, ClickhouseDestroyTablesMixin, BaseT
key=str(cohort_id) + "_0",
created_by=self.user,
)
- AsyncCohortDeletion().run()
+ sweep_cohort_deletions()
self.assertRowCount(0, "cohortpeople")
- @snapshot_clickhouse_queries
def test_delete_cohortpeople_version(self):
cohort_id = 3
team = self.teams[0]
@@ -464,10 +462,40 @@ class TestAsyncDeletion(ClickhouseTestMixin, ClickhouseDestroyTablesMixin, BaseT
key=str(cohort_id) + "_3",
created_by=self.user,
)
- AsyncCohortDeletion().run()
+ sweep_cohort_deletions()
self.assertRowCount(1, "cohortpeople")
+ def test_marking_verified_respects_the_versions_that_survive(self):
+ team = self.teams[0]
+ # Rows sit at version 5 for both cohorts.
+ self._insert_cohortpeople_row(team, uuid4(), 11, 5)
+ self._insert_cohortpeople_row(team, uuid4(), 12, 5)
+
+ AsyncDeletion.objects.create(deletion_type=DeletionType.Cohort_stale, team_id=team.pk, key="11_2")
+ AsyncDeletion.objects.create(deletion_type=DeletionType.Cohort_stale, team_id=team.pk, key="12_9")
+
+ sweep_cohort_deletions()
+
+ # Cohort 11 asked for versions below 2 and nothing is below 2, so it is done.
+ assert AsyncDeletion.objects.get(key="11_2").delete_verified_at is not None
+ # Cohort 12 asked for versions below 9 and version 5 is still there, so it is not.
+ # Verifying it here would abandon that row for good, since the tombstone is the only record.
+ assert AsyncDeletion.objects.get(key="12_9").delete_verified_at is None
+
+ def test_a_team_scoped_key_sweeps_instead_of_raising(self):
+ team = self.teams[0]
+ self._insert_cohortpeople_row(team, uuid4(), 13)
+
+ # `posthog/api/cohort.py` appends the team id for a team that is not the cohort's own.
+ # Unpacking that into two parts raised ValueError and took down the whole pass.
+ AsyncDeletion.objects.create(
+ deletion_type=DeletionType.Cohort_full, team_id=team.pk, key=f"13_0_{self.teams[1].pk}"
+ )
+
+ assert sweep_cohort_deletions().failed == ()
+ self.assertRowCount(0, "cohortpeople")
+
def assertRowCount(self, expected, table="events"):
result = sync_execute(f"SELECT count() FROM {table}")[0][0]
self.assertEqual(result, expected)
diff --git a/posthog/models/test/test_delete_cohorts.py b/posthog/models/test/test_delete_cohorts.py
new file mode 100644
index 000000000000..efbc5ce5949e
--- /dev/null
+++ b/posthog/models/test/test_delete_cohorts.py
@@ -0,0 +1,195 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import patch
+
+from django.test import TestCase
+
+from parameterized import parameterized
+
+from posthog.models import AsyncDeletion, DeletionType, Organization, Team
+from posthog.models.async_deletion.delete_cohorts import (
+ CohortDeleteTarget,
+ CohortKey,
+ MutationCounts,
+ _collapse,
+ _mark_verified,
+ sweep_cohort_deletions,
+)
+
+NOW = datetime(2026, 1, 1, tzinfo=UTC)
+
+
+def counts_of(seen: int, unfinished: int) -> MutationCounts:
+ return MutationCounts(seen=seen, unfinished=unfinished)
+
+
+class TestCollapseCohortDeletions(TestCase):
+ def setUp(self):
+ super().setUp()
+ self.organization = Organization.objects.create(name="test")
+ self.team = Team.objects.create(organization=self.organization)
+
+ def _queue(self, deletion_type: DeletionType, *keys: str, team_id: int | None = None) -> None:
+ AsyncDeletion.objects.bulk_create(
+ AsyncDeletion(deletion_type=deletion_type, team_id=team_id or self.team.pk, key=key) for key in keys
+ )
+
+ @parameterized.expand(
+ [
+ # `posthog/api/cohort.py` appends the team id when the row is for a team other than the
+ # cohort's own, so a key can carry three parts. Unpacking it into two raised ValueError
+ # and took the whole pass with it.
+ ("team_scoped_three_part_key", ["7_3_5512"], 7, None),
+ ("plain_two_part_key", ["7_3"], 7, None),
+ # A cohort that was never calculated writes its version as the literal "None".
+ ("uncalculated_version", ["7_None"], 7, None),
+ ("mixed_shapes_one_cohort", ["7_1", "7_2_5512", "7_None"], 7, None),
+ ]
+ )
+ def test_full_deletion_keys_collapse_to_one_target(self, _name, keys, cohort_id, _unused):
+ self._queue(DeletionType.Cohort_full, *keys)
+
+ targets = _collapse(DeletionType.Cohort_full)
+
+ assert targets == [CohortDeleteTarget(team_id=self.team.pk, cohort_id=cohort_id, below_version=None)]
+
+ @parameterized.expand(
+ [
+ # OR of `version < Vi` is `version < max(Vi)`, so the bound must be the largest.
+ ("ascending", ["9_1", "9_2", "9_7"], 7),
+ ("descending", ["9_7", "9_2", "9_1"], 7),
+ ("team_scoped_keys_carry_versions_too", ["9_3_5512", "9_11_5513"], 11),
+ ("single", ["9_4"], 4),
+ ]
+ )
+ def test_stale_deletions_collapse_to_the_highest_version(self, _name, keys, expected_bound):
+ self._queue(DeletionType.Cohort_stale, *keys)
+
+ targets = _collapse(DeletionType.Cohort_stale)
+
+ assert targets == [CohortDeleteTarget(team_id=self.team.pk, cohort_id=9, below_version=expected_bound)]
+
+ def test_one_cohort_queued_for_many_teams_stays_one_target_per_team(self):
+ other = Team.objects.create(organization=self.organization)
+ # The shape that made the queue unbounded: one deleted cohort, one row per team that saw it.
+ self._queue(DeletionType.Cohort_full, *[f"12_{v}" for v in range(50)])
+ self._queue(DeletionType.Cohort_full, *[f"12_{v}_{other.pk}" for v in range(50)], team_id=other.pk)
+
+ targets = _collapse(DeletionType.Cohort_full)
+
+ assert sorted(targets, key=lambda t: t.team_id) == sorted(
+ [
+ CohortDeleteTarget(team_id=self.team.pk, cohort_id=12, below_version=None),
+ CohortDeleteTarget(team_id=other.pk, cohort_id=12, below_version=None),
+ ],
+ key=lambda t: t.team_id,
+ )
+
+ def test_verified_deletions_are_not_swept_again(self):
+ self._queue(DeletionType.Cohort_full, "3_1", "4_1")
+ AsyncDeletion.objects.filter(key="3_1").update(delete_verified_at="2026-01-01T00:00:00Z")
+
+ assert _collapse(DeletionType.Cohort_full) == [
+ CohortDeleteTarget(team_id=self.team.pk, cohort_id=4, below_version=None)
+ ]
+
+ def test_max_cohorts_caps_targets_and_leaves_the_rest_queued(self):
+ self._queue(DeletionType.Cohort_full, *[f"{cohort}_1" for cohort in range(10)])
+
+ targets = _collapse(DeletionType.Cohort_full, limit=3)
+
+ assert [target.cohort_id for target in targets] == [0, 1, 2]
+ assert AsyncDeletion.objects.filter(delete_verified_at__isnull=True).count() == 10
+
+ @parameterized.expand([("no_underscore", "451"), ("not_a_number", "cohort_3"), ("empty", "")])
+ def test_keys_that_name_no_cohort_are_skipped_rather_than_raising(self, _name, key):
+ self._queue(DeletionType.Cohort_full, key, "8_1")
+
+ # A key the producer never wrote cannot match cohort rows, so dropping it loses no deletion;
+ # what matters is that one such row does not take the whole pass down.
+ assert _collapse(DeletionType.Cohort_full) == [
+ CohortDeleteTarget(team_id=self.team.pk, cohort_id=8, below_version=None)
+ ]
+
+ def test_stale_keys_without_a_numeric_version_carry_no_bound_and_are_skipped(self):
+ self._queue(DeletionType.Cohort_stale, "8_None", "9_2")
+
+ # An unbounded stale sweep would delete every version of cohort 8, which is what
+ # Cohort_full means, not Cohort_stale.
+ assert _collapse(DeletionType.Cohort_stale) == [
+ CohortDeleteTarget(team_id=self.team.pk, cohort_id=9, below_version=2)
+ ]
+
+ def test_an_undrained_table_fails_the_run_instead_of_reporting_a_failed_pass(self):
+ self._queue(DeletionType.Cohort_full, "5_1")
+
+ # The job chains the person sweep on this returning, and the two must not mutate at the
+ # same time. Recording the drain as a failed pass would let the person sweep start anyway.
+ # The first count clears the capacity check so a mutation is enqueued; it then never drains.
+ with (
+ patch("posthog.models.async_deletion.delete_cohorts.sync_execute", return_value=[]),
+ patch("posthog.models.async_deletion.delete_cohorts._server_now", return_value=NOW),
+ patch("posthog.models.async_deletion.delete_cohorts._cleared", return_value=set()),
+ patch(
+ "posthog.models.async_deletion.delete_cohorts._mutation_counts",
+ side_effect=[counts_of(0, 0), *[counts_of(1, 1)] * 40],
+ ),
+ patch("posthog.models.async_deletion.delete_cohorts.time.sleep"),
+ patch("posthog.models.async_deletion.delete_cohorts.time.monotonic", side_effect=range(0, 100_000, 500)),
+ ):
+ with pytest.raises(TimeoutError, match="unfinished mutation"):
+ sweep_cohort_deletions()
+
+ def test_a_capacity_timeout_is_a_failed_pass_because_nothing_was_enqueued(self):
+ self._queue(DeletionType.Cohort_full, "7_1")
+
+ # Another mutation holding the table means this sweep started nothing, so there is no
+ # overlap to prevent and the run continues to the person sweep.
+ with (
+ patch("posthog.models.async_deletion.delete_cohorts.sync_execute", return_value=[]),
+ patch("posthog.models.async_deletion.delete_cohorts._server_now", return_value=NOW),
+ patch("posthog.models.async_deletion.delete_cohorts._cleared", return_value=set()),
+ # Mirrors the real filter: mutations older than this run are invisible to the drain.
+ patch(
+ "posthog.models.async_deletion.delete_cohorts._mutation_counts",
+ side_effect=lambda since=None: counts_of(0, 0) if since else counts_of(9, 9),
+ ),
+ patch("posthog.models.async_deletion.delete_cohorts.time.sleep"),
+ patch("posthog.models.async_deletion.delete_cohorts.time.monotonic", side_effect=range(0, 100_000, 500)),
+ ):
+ assert sweep_cohort_deletions().failed == ("run:Cohort_full",)
+
+ def test_the_drain_waits_for_enqueued_mutations_to_become_visible(self):
+ self._queue(DeletionType.Cohort_full, "6_1")
+
+ # A mutation entry replicates through Keeper, so right after the ALTER the queried host can
+ # report nothing unfinished simply because it does not know about it yet. Treating that gap
+ # as a finished drain releases the person sweep on top of a running mutation.
+ counts = [counts_of(0, 0), counts_of(0, 0), counts_of(1, 1), counts_of(1, 0)]
+ with (
+ patch("posthog.models.async_deletion.delete_cohorts.sync_execute", return_value=[]),
+ patch("posthog.models.async_deletion.delete_cohorts._server_now", return_value=NOW),
+ patch("posthog.models.async_deletion.delete_cohorts._cleared", return_value=set()),
+ patch(
+ "posthog.models.async_deletion.delete_cohorts._mutation_counts", side_effect=counts
+ ) as mutation_counts,
+ patch("posthog.models.async_deletion.delete_cohorts.time.sleep"),
+ patch("posthog.models.async_deletion.delete_cohorts.time.monotonic", side_effect=range(100)),
+ ):
+ assert sweep_cohort_deletions().failed == ()
+
+ assert mutation_counts.call_count == len(counts)
+
+ def test_marking_pages_over_every_queued_row(self):
+ # The marking pass walks the primary key in pages. An off-by-one on the page boundary would
+ # skip rows silently, leaving them queued forever with their ClickHouse rows already gone.
+ self._queue(DeletionType.Cohort_full, *[f"20_{v}" for v in range(7)])
+ self._queue(DeletionType.Cohort_full, "21_0")
+ cleared = {CohortKey(team_id=self.team.pk, cohort_id=20)}
+
+ with patch("posthog.models.async_deletion.delete_cohorts.COHORT_MARK_PAGE_SIZE", 2):
+ assert _mark_verified(DeletionType.Cohort_full, cleared).marked == 7
+
+ assert AsyncDeletion.objects.filter(delete_verified_at__isnull=True).count() == 1
+ assert AsyncDeletion.objects.get(delete_verified_at__isnull=True).key == "21_0"