:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(deletions): report rows deletes_job left behind (#90689)
Paweł Szczurc54571af6fc8
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex b382a4424f81..2f7b422fb0d2 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -39,6 +39,8 @@ Two gates keep that from passing silently.- `placement_for` refuses a registered target whose storage table is on no data node of any cluster reachable from here while its Distributed proxy still returns rows (`UnreachableTargetError`). Absent from everywhere and empty is still treated as not yet migrated, which is the ordinary pre-rollout state.- `assert_sweep_complete` runs after the immediate person-removal and event-removal sweeps and counts survivors through the proxy, so rows a mutation never reached fail the request instead of completing it (`UnsweptRowsError`).+- `deletes_job` counts the same way after its own sweep, but only logs what survived and still marks the requests verified. Its mutations have already run by then, and failing the op would strand the run without undoing anything. Proving zero survivors is a full scan, so the count is time-bounded and reports unknown rather than zero when it runs out.+- A proxy only reads the cluster its engine names, and `sql.py` builds the `events_json` proxy against `CLICKHOUSE_CLUSTER`. So a target stored on another cluster is counted twice: once through the proxy, and once on its storage table through the handle that holds it. Without the second count, a deployment whose storage moved without the proxy following it would report a clean sweep off an empty table.Both gates probe hosts rather than compare cluster names.Two cluster names can cover the same nodes, which is what the dev stack and CI do, so a name comparison would refuse deployments that can in fact sweep the table.diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex bc04f3233e8d..7c413782a8c7 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -1,8 +1,10 @@import abcimport timeimport uuid+from collections.abc import Callablefrom dataclasses import dataclassfrom datetime import datetime+from functools import partialfrom django.conf import settingsfrom django.db.models import Q@@ -33,7 +35,7 @@ from posthog.dags.common.staged_dictionary import (from posthog.dags.person_overrides import squash_person_overridesfrom posthog.dataclasses import frozenfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.deletion_targets import resolve_placements, sweep_clusters+from posthog.models.deletion_targets import COVERAGE_DOC, resolve_placements, surviving_rows_sql, sweep_clustersfrom posthog.models.event.deletion import events_data_tablesfrom posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.group.sql import GROUPS_TABLE@@ -71,6 +73,12 @@ class DeleteConfig(dagster.Config):default=0,description="The maximum amount of memory to use for the dictionary, or 0 to use an unlimited amount.",)+ verification_max_execution_time: int = pydantic.Field(+ default=300,+ description="Seconds to spend counting rows the sweep should have removed but did not. Proving none "+ "survive is a full scan, so the count is bounded and a count that runs out of time is reported as "+ "unknown rather than as zero.",+ )@propertydef parsed_timestamp(self) -> datetime:@@ -110,6 +118,16 @@ class MonthlyCleanupConfig(dagster.Config):)+# Reads only team_id, person_id, timestamp and uuid, which every registered target declares, so it+# applies unchanged to all of them. Shared with the post-sweep count so what gets verified is+# exactly what got deleted.+_DELETE_PREDICATE = """or(+ (dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id)) AND timestamp <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))),+ (dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))),+ (dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid)))+)"""++ShardMutations = dict[int, MutationWaiters]# Shard numbers are per cluster, so a sweep spanning two of them cannot key its waiters by shard# alone. Keyed by cluster name rather than by handle: the handle is recovered with@@ -674,26 +692,16 @@ def delete_events()# Every registered target must get this delete, or rows survive on the table that got skipped.- # The predicate below reads only team_id, person_id, timestamp and uuid, which every target- # declares, so it applies unchanged to all of them.placements = resolve_placements(cluster)delete_mutation_runners = [(placement,LightweightDeleteMutationRunner(table=placement.target.data_table,- predicate="""or(- (dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id)) AND timestamp <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))),- (dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))),- (dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid)))- )- """,- parameters={- "pending_deletes_dictionary": load_and_verify_deletes_dictionary.qualified_name,- "person_deletion_type": DeletionType.Person,- "team_deletion_type": DeletionType.Team,- "adhoc_event_deletes_dictionary": load_and_verify_adhoc_event_deletes_dictionary.qualified_name,- },+ predicate=_DELETE_PREDICATE,+ parameters=_delete_predicate_params(+ load_and_verify_deletes_dictionary, load_and_verify_adhoc_event_deletes_dictionary+ ),),)for placement in placements@@ -824,12 +832,122 @@ class VerifiedDeletionResources:adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary+def _delete_predicate_params(+ pending_deletes_dictionary: "PendingDeletesDictionary",+ adhoc_event_deletes_dictionary: "AdhocEventDeletesDictionary",+) -> dict[str, str | int]:+ return {+ "pending_deletes_dictionary": pending_deletes_dictionary.qualified_name,+ "person_deletion_type": DeletionType.Person,+ "team_deletion_type": DeletionType.Team,+ "adhoc_event_deletes_dictionary": adhoc_event_deletes_dictionary.qualified_name,+ }+++def _rows_from_any_host(cluster: ClickhouseCluster, query: Query) -> list:+ return [cluster.any_host_by_role(query, NodeRole.DATA).result()]+++def _rows_per_shard(cluster: ClickhouseCluster, query: Query) -> list:+ return list(cluster.map_one_host_per_shard(query).result().values())+++def _count_through(+ context: dagster.OpExecutionContext,+ runner: Callable[[Query], list],+ table: str,+ params: dict[str, str | int],+ max_execution_time: int,+) -> int | None:+ """Survivors on ``table``, or None when the count could not be taken.++ None is deliberately not zero: a count that errored or ran out of time says nothing about+ whether rows remain, and reporting it as clean is the mistake worth avoiding here.+ """+ query = Query(+ surviving_rows_sql(table, _DELETE_PREDICATE),+ params,+ settings={"max_execution_time": str(max_execution_time)},+ )+ try:+ return sum(int(rows[0][0]) if rows else 0 for rows in runner(query))+ except Exception as e:+ context.log.warning(f"Could not count what survived the sweep in {table}: {e}")+ return None+++def _count_unswept_rows(+ context: dagster.OpExecutionContext,+ cluster: ClickhouseCluster,+ pending_deletes_dictionary: "PendingDeletesDictionary",+ adhoc_event_deletes_dictionary: "AdhocEventDeletesDictionary",+ max_execution_time: int,+) -> dict[str, int | None]:+ """Count rows this run was supposed to remove and that are still readable, per table.++ Two counts, because neither alone is trustworthy.++ The Distributed proxy sees rows no mutation reached, including a shard this handle does not+ enumerate. But it only reads the cluster its engine names, and this repo builds the events_json+ proxy against CLICKHOUSE_CLUSTER, so on a deployment whose storage moved elsewhere the proxy+ can read an empty table and report a clean sweep.++ So a target stored on another cluster is also counted on its storage table, through the handle+ that holds it. That answers "did the mutation we dispatched actually remove these" without+ depending on how the proxy is defined. Targets on the job's own cluster skip it, since there+ the proxy already names the cluster the rows are on.++ Proving zero survivors is a full scan of the events tables, so each count is bounded rather+ than left to run for as long as it takes.+ """+ params = _delete_predicate_params(pending_deletes_dictionary, adhoc_event_deletes_dictionary)+ counts: dict[str, int | None] = {}+ for placement in resolve_placements(cluster):+ counts[placement.target.read_table] = _count_through(+ context,+ partial(_rows_from_any_host, cluster),+ placement.target.read_table,+ params,+ max_execution_time,+ )+ if placement.cluster is not cluster:+ counts[placement.target.data_table] = _count_through(+ context,+ partial(_rows_per_shard, placement.cluster),+ placement.target.data_table,+ params,+ max_execution_time,+ )+ return counts++@dagster.opdef mark_deletions_verified(+ context: dagster.OpExecutionContext,+ config: DeleteConfig,cluster: dagster.ResourceParam[ClickhouseCluster],pending_deletions_dictionary: PendingDeletesDictionary,adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary,) -> VerifiedDeletionResources:+ # Only a report. The mutations have already run, the requests are marked verified either way,+ # and failing here would strand the run without undoing anything. It exists so a sweep that+ # removed nothing leaves a trace rather than passing as a clean run.+ unswept = _count_unswept_rows(+ context,+ cluster,+ pending_deletions_dictionary,+ adhoc_event_deletes_dictionary,+ config.verification_max_execution_time,+ )+ remaining = {table: count for table, count in unswept.items() if count}+ if remaining:+ context.log.error(+ "The sweep finished and rows it should have removed are still readable: "+ + ", ".join(f"{table}={count}" for table, count in remaining.items())+ + f". Marking these requests verified anyway. See {COVERAGE_DOC}."+ )+ context.add_output_metadata({"unswept_rows": dagster.MetadataValue.json(unswept)})+now = timezone.now()deletion_ids = [iddiff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex c19f705af501..f61c46202537 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -5,17 +5,25 @@ from uuid import UUIDimport pytestfrom freezegun import freeze_time+from unittest.mock import patch++from django.conf import settings as django_settingsfrom clickhouse_driver import Client+from dagster import build_op_context-from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunnerfrom posthog.dags.deletes import (+ _DELETE_PREDICATE,AdhocEventDeletesDictionary,AdhocEventDeletesTable,+ DeleteConfig,MonthlyCleanupConfig,PendingDeletesDictionary,PendingDeletesTable,StagedDictionary,+ _count_unswept_rows,+ _delete_predicate_params,cleanup_old_events_by_partition,deletes_job,find_partitions_to_cleanup,@@ -23,6 +31,8 @@ from posthog.dags.deletes import ()from posthog.dags.tests.conftest import insert_flag_evaluationsfrom posthog.models.async_deletion import AsyncDeletion, DeletionType+from posthog.models.deletion_targets import EVENTS, TargetPlacement+from posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE@@ -781,3 +791,135 @@ def test_a_rerun_stages_over_the_previous_runs_object(cluster: ClickhouseClusterfinally:cluster.any_host(dictionary.drop).result()cluster.any_host(table.drop).result()+++def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: ClickhouseCluster):+ # The count only earns its place if it can come back non-zero. A predicate or parameter that+ # matched nothing would report a clean sweep every week and nobody would notice.+ team_id = 424242+ person_uuid = UUID(int=7)+ timestamp = datetime(2026, 8, 27, 10, 0, 0)++ table = PendingDeletesTable(timestamp=timestamp)+ dictionary = PendingDeletesDictionary(source=table)+ adhoc = AdhocEventDeletesDictionary(source=AdhocEventDeletesTable())+ create = partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)+ create_adhoc = partial(adhoc.create, shards=1, max_execution_time=0, max_memory_usage=0)++ def insert_person_deletion(client: Client) -> None:+ client.execute(+ table.populate_query,+ [+ {+ "id": 1,+ "deletion_type": int(DeletionType.Person),+ "key": str(person_uuid),+ "group_type_index": None,+ "created_at": timestamp,+ "delete_verified_at": None,+ "created_by_id": None,+ "team_id": team_id,+ }+ ],+ )++ def insert_events(client: Client) -> None:+ client.execute(+ "INSERT INTO writable_events (team_id, distinct_id, person_id, timestamp) VALUES",+ [(team_id, "d", person_uuid, timestamp - timedelta(hours=1))],+ )++ try:+ cluster.any_host(table.create).result()+ cluster.any_host(insert_person_deletion).result()+ cluster.any_host(create).result()+ cluster.any_host(dictionary.load).result()+ cluster.any_host(create_adhoc).result()+ cluster.any_host(adhoc.load).result()+ cluster.any_host(insert_events).result()++ context = build_op_context()+ before = _count_unswept_rows(+ context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time+ )+ surviving = before["events"]+ assert surviving is not None and surviving >= 1, "the count cannot see rows the sweep has not removed yet"++ runner = LightweightDeleteMutationRunner(+ table=EVENTS_DATA_TABLE(),+ predicate=_DELETE_PREDICATE,+ parameters=_delete_predicate_params(dictionary, adhoc),+ )+ for _host, mutation in cluster.map_one_host_per_shard(runner).result().items():+ cluster.map_all_hosts(mutation.wait).result()++ after = _count_unswept_rows(context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time)+ assert after["events"] == 0+ finally:+ cluster.any_host(dictionary.drop).result()+ cluster.any_host(adhoc.drop).result()+ cluster.any_host(table.drop).result()+++def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(cluster: ClickhouseCluster):+ # The proxy count only reads the cluster the Distributed engine names, and this repo builds the+ # events_json proxy against CLICKHOUSE_CLUSTER. A deployment whose storage moved elsewhere would+ # get a clean report off an empty table, so an off-cluster target is counted on its storage+ # table too, through the handle that holds it.+ team_id = 424243+ person_uuid = UUID(int=11)+ timestamp = datetime(2026, 8, 28, 10, 0, 0)++ table = PendingDeletesTable(timestamp=timestamp)+ dictionary = PendingDeletesDictionary(source=table)+ adhoc = AdhocEventDeletesDictionary(source=AdhocEventDeletesTable())++ def insert_person_deletion(client: Client) -> None:+ client.execute(+ table.populate_query,+ [+ {+ "id": 2,+ "deletion_type": int(DeletionType.Person),+ "key": str(person_uuid),+ "group_type_index": None,+ "created_at": timestamp,+ "delete_verified_at": None,+ "created_by_id": None,+ "team_id": team_id,+ }+ ],+ )++ def insert_events(client: Client) -> None:+ client.execute(+ "INSERT INTO writable_events (team_id, distinct_id, person_id, timestamp) VALUES",+ [(team_id, "d", person_uuid, timestamp - timedelta(hours=1))],+ )++ # A second handle over the same node stands in for a target whose storage is elsewhere.+ sibling = cluster.sibling(django_settings.CLICKHOUSE_SINGLE_SHARD_CLUSTER)+ placement = TargetPlacement(target=EVENTS, cluster=sibling)++ try:+ cluster.any_host(table.create).result()+ cluster.any_host(insert_person_deletion).result()+ cluster.any_host(partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()+ cluster.any_host(dictionary.load).result()+ cluster.any_host(partial(adhoc.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()+ cluster.any_host(adhoc.load).result()+ cluster.any_host(insert_events).result()++ with patch("posthog.dags.deletes.resolve_placements", return_value=[placement]):+ counts = _count_unswept_rows(+ build_op_context(), cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time+ )++ storage = counts[EVENTS.data_table]+ assert storage is not None and storage >= 1, "the storage table was not counted for an off-cluster target"+ finally:+ cluster.any_host(dictionary.drop).result()+ cluster.any_host(adhoc.drop).result()+ cluster.any_host(table.drop).result()