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(clickhouse): add the cleanup sweep's persisted snapshot tables (#80943)

Eli Reisman046dd76590ee
diff --git a/posthog/clickhouse/cleanup_snapshots.py b/posthog/clickhouse/cleanup_snapshots.py
new file mode 100644
index 000000000000..9b0907e0be74
--- /dev/null
+++ b/posthog/clickhouse/cleanup_snapshots.py
@@ -0,0 +1,145 @@
+"""Persisted worklists for the weekly ClickHouse cleanup sweep.
+
+The sweep destroys the tombstones its own worklists are derived from, so each stage has to be
+frozen before the first mutation. Runs share these tables and scope their rows by `run_id`
+instead of each creating and dropping their own, which would churn table DDL across every node
+every week. `run_id` leads every sort key so a run reads only its own rows through the primary
+index.
+"""
+
+from posthog.clickhouse.table_engines import ReplacingMergeTree
+
+CLEANUP_DELETED_PERSONS_TABLE = "clickhouse_cleanup_deleted_persons"
+CLEANUP_REVIVED_PERSONS_TABLE = "clickhouse_cleanup_revived_persons"
+CLEANUP_ORPHANED_DISTINCT_IDS_TABLE = "clickhouse_cleanup_orphaned_distinct_ids"
+CLEANUP_REVIVED_DISTINCT_IDS_TABLE = "clickhouse_cleanup_revived_distinct_ids"
+
+# A run's rows stay readable for a fortnight so a failed weekly sweep can still be inspected on the
+# next working day. A successful run clears its own rows, so this only ever covers failures.
+CLEANUP_SNAPSHOT_TTL_DAYS = 14
+
+
+def _cleanup_snapshot_table_sql(table_name: str, columns: str, sort_key: str) -> str:
+ # Partitioning by run id makes clearing a finished run a metadata-only DROP PARTITION instead
+ # of a mutation that rewrites every part. created_at is the ReplacingMergeTree version, and
+ # its sub-second resolution is what makes a retried populate deterministic: two inserts of the
+ # same key in the same second would otherwise tie and let merge order pick the survivor.
+ # ttl_only_drop_parts stops TTL merges from rewriting a part that holds any expired row; the
+ # TTL is a backstop for failed runs, so reclaiming whole parts late beats weekly rewrites.
+ return """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ run_id String,
+ {columns},
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = {engine}
+PARTITION BY run_id
+ORDER BY (run_id, {sort_key})
+TTL created_at + INTERVAL {ttl_days} DAY
+SETTINGS ttl_only_drop_parts = 1
+""".format(
+ table_name=table_name,
+ columns=columns,
+ engine=ReplacingMergeTree(table_name, ver="created_at"),
+ sort_key=sort_key,
+ ttl_days=CLEANUP_SNAPSHOT_TTL_DAYS,
+ )
+
+
+def _drop_cleanup_snapshot_table_sql(table_name: str) -> str:
+ return f"""
+DROP TABLE IF EXISTS {table_name}
+"""
+
+
+def CLEANUP_DELETED_PERSONS_TABLE_SQL():
+ """Persons the run will delete, one row each, with the version the run observed as latest.
+
+ `max_version` bounds the delete so a version written after the snapshot survives a run that
+ never saw it. It matches `person.version` (UInt64) so the dictionary attribute the delete
+ predicate reads compares against the source column without promotion.
+ """
+ return _cleanup_snapshot_table_sql(
+ CLEANUP_DELETED_PERSONS_TABLE,
+ "team_id Int64, person_id UUID, max_version UInt64",
+ "team_id, person_id",
+ )
+
+
+def CLEANUP_REVIVED_PERSONS_TABLE_SQL():
+ """Snapshotted persons that came back to life mid-run, and so must not be deleted.
+
+ Every dictionary over the worklists anti-joins this table, which is how a checkpoint drops a
+ key without mutating the worklist it came from.
+ """
+ return _cleanup_snapshot_table_sql(
+ CLEANUP_REVIVED_PERSONS_TABLE,
+ "team_id Int64, person_id UUID",
+ "team_id, person_id",
+ )
+
+
+def CLEANUP_ORPHANED_DISTINCT_IDS_TABLE_SQL():
+ """Distinct id mappings the run will delete, with the reason each one qualified.
+
+ `own_tombstone` distinguishes a mapping deleted in its own right from one deleted because its
+ owning person is going away. `max_version` matches `person_distinct_id2.version` (Int64).
+ """
+ return _cleanup_snapshot_table_sql(
+ CLEANUP_ORPHANED_DISTINCT_IDS_TABLE,
+ "team_id Int64, distinct_id String, person_id UUID, own_tombstone UInt8, max_version Int64",
+ "team_id, distinct_id",
+ )
+
+
+def CLEANUP_REVIVED_DISTINCT_IDS_TABLE_SQL():
+ """Snapshotted distinct id mappings that stopped qualifying mid-run."""
+ return _cleanup_snapshot_table_sql(
+ CLEANUP_REVIVED_DISTINCT_IDS_TABLE,
+ "team_id Int64, distinct_id String",
+ "team_id, distinct_id",
+ )
+
+
+def DROP_CLEANUP_DELETED_PERSONS_TABLE_SQL():
+ return _drop_cleanup_snapshot_table_sql(CLEANUP_DELETED_PERSONS_TABLE)
+
+
+def DROP_CLEANUP_REVIVED_PERSONS_TABLE_SQL():
+ return _drop_cleanup_snapshot_table_sql(CLEANUP_REVIVED_PERSONS_TABLE)
+
+
+def DROP_CLEANUP_ORPHANED_DISTINCT_IDS_TABLE_SQL():
+ return _drop_cleanup_snapshot_table_sql(CLEANUP_ORPHANED_DISTINCT_IDS_TABLE)
+
+
+def DROP_CLEANUP_REVIVED_DISTINCT_IDS_TABLE_SQL():
+ return _drop_cleanup_snapshot_table_sql(CLEANUP_REVIVED_DISTINCT_IDS_TABLE)
+
+
+CLEANUP_SNAPSHOT_TABLES = (
+ CLEANUP_DELETED_PERSONS_TABLE,
+ CLEANUP_REVIVED_PERSONS_TABLE,
+ CLEANUP_ORPHANED_DISTINCT_IDS_TABLE,
+ CLEANUP_REVIVED_DISTINCT_IDS_TABLE,
+)
+
+CLEANUP_SNAPSHOT_TABLE_SQL = (
+ CLEANUP_DELETED_PERSONS_TABLE_SQL,
+ CLEANUP_REVIVED_PERSONS_TABLE_SQL,
+ CLEANUP_ORPHANED_DISTINCT_IDS_TABLE_SQL,
+ CLEANUP_REVIVED_DISTINCT_IDS_TABLE_SQL,
+)
+
+DROP_CLEANUP_SNAPSHOT_TABLE_SQL = (
+ DROP_CLEANUP_DELETED_PERSONS_TABLE_SQL,
+ DROP_CLEANUP_REVIVED_PERSONS_TABLE_SQL,
+ DROP_CLEANUP_ORPHANED_DISTINCT_IDS_TABLE_SQL,
+ DROP_CLEANUP_REVIVED_DISTINCT_IDS_TABLE_SQL,
+)
+
+
+def TRUNCATE_CLEANUP_SNAPSHOT_TABLES_SQL():
+ # Unqualified so the test harness can match these against the tables ClickHouse reports as
+ # empty and skip the keeper round-trip.
+ return [f"TRUNCATE TABLE IF EXISTS {table_name}" for table_name in CLEANUP_SNAPSHOT_TABLES]
diff --git a/posthog/clickhouse/hcl/golden/local-multi/data.hcl b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
index 126a68686a1e..544a7a618e5c 100644
--- a/posthog/clickhouse/hcl/golden/local-multi/data.hcl
+++ b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
@@ -389,6 +389,130 @@ database "posthog" {
}
}
+ table "clickhouse_cleanup_deleted_persons" {
+ order_by = ["run_id", "team_id", "person_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "max_version" {
+ type = "UInt64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_deleted_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_orphaned_distinct_ids" {
+ order_by = ["run_id", "team_id", "distinct_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "own_tombstone" {
+ type = "UInt8"
+ }
+ column "max_version" {
+ type = "Int64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_orphaned_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_revived_distinct_ids" {
+ order_by = ["run_id", "team_id", "distinct_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_revived_persons" {
+ order_by = ["run_id", "team_id", "person_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
table "cohort_membership" {
order_by = ["team_id", "cohort_id", "person_id"]
settings = {
diff --git a/posthog/clickhouse/hcl/golden/local-single/all.hcl b/posthog/clickhouse/hcl/golden/local-single/all.hcl
index 668cf082ae3d..6c9e898b265a 100644
--- a/posthog/clickhouse/hcl/golden/local-single/all.hcl
+++ b/posthog/clickhouse/hcl/golden/local-single/all.hcl
@@ -416,6 +416,130 @@ database "posthog" {
}
}
+ table "clickhouse_cleanup_deleted_persons" {
+ order_by = ["run_id", "team_id", "person_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "max_version" {
+ type = "UInt64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_deleted_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_orphaned_distinct_ids" {
+ order_by = ["run_id", "team_id", "distinct_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "own_tombstone" {
+ type = "UInt8"
+ }
+ column "max_version" {
+ type = "Int64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_orphaned_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_revived_distinct_ids" {
+ order_by = ["run_id", "team_id", "distinct_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
+ table "clickhouse_cleanup_revived_persons" {
+ order_by = ["run_id", "team_id", "person_id"]
+ partition_by = "run_id"
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+
table "cohort_membership" {
order_by = ["team_id", "cohort_id", "person_id"]
settings = {
diff --git a/posthog/clickhouse/hcl/roles/data/local/tables.hcl b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
index 6e94e54a464d..1c5ba0162867 100644
--- a/posthog/clickhouse/hcl/roles/data/local/tables.hcl
+++ b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
@@ -245,6 +245,126 @@ database "posthog" {
replica_name = "{replica}-{shard}"
}
}
+ table "clickhouse_cleanup_deleted_persons" {
+ partition_by = "run_id"
+ order_by = ["run_id", "team_id", "person_id"]
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "max_version" {
+ type = "UInt64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_deleted_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+ table "clickhouse_cleanup_orphaned_distinct_ids" {
+ partition_by = "run_id"
+ order_by = ["run_id", "team_id", "distinct_id"]
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "own_tombstone" {
+ type = "UInt8"
+ }
+ column "max_version" {
+ type = "Int64"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_orphaned_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+ table "clickhouse_cleanup_revived_distinct_ids" {
+ partition_by = "run_id"
+ order_by = ["run_id", "team_id", "distinct_id"]
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_distinct_ids"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
+ table "clickhouse_cleanup_revived_persons" {
+ partition_by = "run_id"
+ order_by = ["run_id", "team_id", "person_id"]
+ ttl = "created_at + toIntervalDay(14)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "run_id" {
+ type = "String"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "now64()"
+ }
+ engine "replicated_replacing_merge_tree" {
+ zoo_path = "/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_persons"
+ replica_name = "{replica}-{shard}"
+ version_column = "created_at"
+ }
+ }
table "cohort_membership" {
order_by = ["team_id", "cohort_id", "person_id"]
settings = {
diff --git a/posthog/clickhouse/hcl/sql/local-multi/data.sql b/posthog/clickhouse/hcl/sql/local-multi/data.sql
index 8ede6add2d6c..b925c1afdf0a 100644
--- a/posthog/clickhouse/hcl/sql/local-multi/data.sql
+++ b/posthog/clickhouse/hcl/sql/local-multi/data.sql
@@ -77,6 +77,34 @@ CREATE TABLE posthog.channel_definition (
type_if_paid Nullable(String),
type_if_organic Nullable(String)
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.channel_definition', '{replica}-{shard}') ORDER BY (domain, kind) SETTINGS index_granularity = 8192;
+CREATE TABLE posthog.clickhouse_cleanup_deleted_persons (
+ run_id String,
+ team_id Int64,
+ person_id UUID,
+ max_version UInt64,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_deleted_persons', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, person_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_orphaned_distinct_ids (
+ run_id String,
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ own_tombstone UInt8,
+ max_version Int64,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_orphaned_distinct_ids', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, distinct_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_revived_distinct_ids (
+ run_id String,
+ team_id Int64,
+ distinct_id String,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_distinct_ids', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, distinct_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_revived_persons (
+ run_id String,
+ team_id Int64,
+ person_id UUID,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_persons', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, person_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
CREATE TABLE posthog.cohort_membership (
team_id Int64,
cohort_id Int64,
diff --git a/posthog/clickhouse/hcl/sql/local-single/all.sql b/posthog/clickhouse/hcl/sql/local-single/all.sql
index 84ee8c2492b4..c62e800eb3f5 100644
--- a/posthog/clickhouse/hcl/sql/local-single/all.sql
+++ b/posthog/clickhouse/hcl/sql/local-single/all.sql
@@ -15,6 +15,34 @@ CREATE TABLE posthog.channel_definition (
type_if_paid Nullable(String),
type_if_organic Nullable(String)
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.channel_definition', '{replica}-{shard}') ORDER BY (domain, kind) SETTINGS index_granularity = 8192;
+CREATE TABLE posthog.clickhouse_cleanup_deleted_persons (
+ run_id String,
+ team_id Int64,
+ person_id UUID,
+ max_version UInt64,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_deleted_persons', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, person_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_orphaned_distinct_ids (
+ run_id String,
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ own_tombstone UInt8,
+ max_version Int64,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_orphaned_distinct_ids', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, distinct_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_revived_distinct_ids (
+ run_id String,
+ team_id Int64,
+ distinct_id String,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_distinct_ids', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, distinct_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.clickhouse_cleanup_revived_persons (
+ run_id String,
+ team_id Int64,
+ person_id UUID,
+ created_at DateTime64(6, 'UTC') DEFAULT now64()
+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.clickhouse_cleanup_revived_persons', '{replica}-{shard}', created_at) ORDER BY (run_id, team_id, person_id) PARTITION BY run_id TTL created_at + toIntervalDay(14) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
CREATE TABLE posthog.cohort_membership (
team_id Int64,
cohort_id Int64,
diff --git a/posthog/clickhouse/migrations/0310_add_cleanup_snapshot_tables.py b/posthog/clickhouse/migrations/0310_add_cleanup_snapshot_tables.py
new file mode 100644
index 000000000000..019e77a1964d
--- /dev/null
+++ b/posthog/clickhouse/migrations/0310_add_cleanup_snapshot_tables.py
@@ -0,0 +1,6 @@
+from posthog.clickhouse.cleanup_snapshots import CLEANUP_SNAPSHOT_TABLE_SQL
+from posthog.clickhouse.client.migration_tools import NodeRole, run_sql_with_exceptions
+
+operations = [
+ run_sql_with_exceptions(table_sql(), node_roles=[NodeRole.DATA]) for table_sql in CLEANUP_SNAPSHOT_TABLE_SQL
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 72425daf786c..852caf500265 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0309_metrics_kafka_ingest
+0310_add_cleanup_snapshot_tables
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 53d0627e4b9a..b9ed597ecf43 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -89,6 +89,7 @@ def create_clickhouse_tables():
def reset_clickhouse_tables():
# Truncate clickhouse tables to default before running test
# Mostly so that test runs locally work correctly
+ from posthog.clickhouse.cleanup_snapshots import TRUNCATE_CLEANUP_SNAPSHOT_TABLES_SQL
from posthog.clickhouse.dead_letter_queue import TRUNCATE_DEAD_LETTER_QUEUE_TABLE_SQL
from posthog.clickhouse.plugin_log_entries import TRUNCATE_PLUGIN_LOG_ENTRIES_TABLE_SQL
from posthog.heatmaps.sql import TRUNCATE_HEATMAPS_TABLE_SQL
@@ -149,6 +150,7 @@ def reset_clickhouse_tables():
TRUNCATE_HEATMAPS_TABLE_SQL(),
TRUNCATE_PG_EMBEDDINGS_TABLE_SQL(),
TRUNCATE_AI_EVENTS_TABLE_SQL(),
+ *TRUNCATE_CLEANUP_SNAPSHOT_TABLES_SQL(),
]
# Drop created Kafka tables because some tests don't expect it.
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.py
new file mode 100644
index 000000000000..e77a48387bcf
--- /dev/null
+++ b/posthog/dags/clickhouse_cleanup.py
@@ -0,0 +1,1187 @@
+"""Weekly ClickHouse cleanup sweeps: deleted cohort memberships, then deleted persons and the
+distinct ids that belonged to them.
+
+ClickHouse cannot cheaply delete individual rows, so deletions are marked and swept later. Every
+sweep issues cluster-wide mutations, and running those at the same time overloads the cluster, so
+the ops below are chained on each other's output to force them into sequence.
+
+The person sweep destroys the tombstones its own worklist is derived from, so the run freezes that
+worklist into a persisted snapshot table first, scoped by run id. Everything downstream, including
+the Postgres handoff, reads the snapshot rather than recomputing it.
+"""
+
+import time
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, replace
+from datetime import UTC, datetime, timedelta
+from functools import partial
+from math import ceil
+
+from django.conf import settings
+
+import dagster
+import pydantic
+import psycopg2.extensions
+from clickhouse_driver.client import Client
+from prometheus_client import Counter
+from psycopg2.extras import execute_values
+
+from posthog.clickhouse.cleanup_snapshots import (
+ CLEANUP_DELETED_PERSONS_TABLE,
+ CLEANUP_ORPHANED_DISTINCT_IDS_TABLE,
+ CLEANUP_REVIVED_DISTINCT_IDS_TABLE,
+ CLEANUP_REVIVED_PERSONS_TABLE,
+ CLEANUP_SNAPSHOT_TABLES,
+)
+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, get_clickhouse_creds
+from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner, MutationWaiter, NodeRole
+from posthog.clickhouse.custom_metrics import MetricsClient
+from posthog.dags.common import JobOwners
+from posthog.dags.common.common import settings_with_log_comment
+from posthog.dags.common.dictionaries import Dictionary
+from posthog.dags.common.staged_dictionary import (
+ StagedDictionary,
+ create_on_every_cluster,
+ load_and_verify_on_every_cluster,
+)
+from posthog.dataclasses import frozen
+from posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions
+from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE, PERSONS_TABLE
+
+logger = dagster.get_dagster_logger(__name__)
+
+REVIVED_PERSON_COUNTER = Counter(
+ "posthog_clickhouse_cleanup_revived_persons_total",
+ "Persons that came back to life between the snapshot and the sweep, and were excluded",
+)
+
+REVIVED_DISTINCT_ID_COUNTER = Counter(
+ "posthog_clickhouse_cleanup_revived_distinct_ids_total",
+ "Distinct id mappings that came back between the snapshot and the sweep, and were excluded",
+)
+
+PG_CLEANUP_QUEUE_TABLE = "person_pg_cleanup_queue"
+
+# How many queued persons travel per ClickHouse read and per Postgres upsert transaction. Bounds
+# the op's memory to one page however large the snapshot is.
+PERSIST_PAGE_SIZE = 50_000
+
+# Each delete runs as one pair of ordered mutations per contiguous team-id range. Batches run in
+# sequence, never in parallel, and ranges do not reduce what a mutation reads or rewrites: merged
+# parts span nearly the whole team-id space, so every extra batch re-reads most parts and
+# re-rewrites their delete masks. Total mutation cost is therefore roughly N times the single
+# batch cost. What batching buys is a bound on one mutation's wall time under the wait deadline,
+# and per-range progress in the logs. The default is 1 because those rarely justify the cost;
+# raise team_batches together with max_persons when draining a large backlog in checkpoints.
+DEFAULT_TEAM_BATCHES = 1
+
+
+class CleanupConfig(dagster.Config):
+ """Read once, by the first op, and carried to every later op on CleanupRun.
+
+ Setting any of these on another op's config has no effect.
+ """
+
+ dry_run: bool = pydantic.Field(
+ default=True,
+ description="Build the snapshot and report what would be removed, without deleting anything.",
+ )
+ cleanup: bool = pydantic.Field(
+ default=True,
+ description="Drop the dictionaries and clear this run's snapshot rows when the run finishes.",
+ )
+ team_batches: int = pydantic.Field(
+ default=DEFAULT_TEAM_BATCHES,
+ description="How many contiguous team ranges to split each delete into.",
+ )
+ shards: int = pydantic.Field(default=16, description="Dictionary SHARDS, which parallelize loading.")
+ max_execution_time: int = pydantic.Field(default=0, description="Dictionary load timeout, 0 for no limit.")
+ max_memory_usage: int = pydantic.Field(default=0, description="Dictionary load memory cap, 0 for no limit.")
+ dictionary_load_timeout: int = pydantic.Field(
+ default=600,
+ description="How long to wait for a dictionary to finish loading on a host before failing the run.",
+ )
+ mutation_stall_timeout: int = pydantic.Field(
+ default=1800,
+ description="Fail a delete batch when attempts keep failing and no part completes for this many seconds.",
+ )
+ 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.",
+ )
+ 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 "
+ "and the next run picks up the rest, because the worklist derives from the tombstones that remain.",
+ )
+ min_team_id: int = pydantic.Field(default=0, description="Only sweep persons with team_id >= this, 0 to disable.")
+ max_team_id: int = pydantic.Field(default=0, description="Only sweep persons with team_id <= this, 0 to disable.")
+
+
+@dataclass(frozen=True)
+class SnapshotTable:
+ """One run's rows in a persisted worklist holding one stage of the sweep.
+
+ Every run writes into the same table and reads back its own rows by run id. Creating and
+ dropping a replicated table per run instead would churn DDL across every node once a week.
+ `run_id` leads the sort key, so a run reads only its own rows through the primary index, and
+ a successful run clears them when it finishes.
+ """
+
+ run_id: str
+
+ @property
+ def table_name(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def keys(self) -> str:
+ """The columns that identify a row within a run."""
+ raise NotImplementedError
+
+ @property
+ def dictionary_types(self) -> str:
+ """The column list a dictionary over this table declares."""
+ raise NotImplementedError
+
+ @property
+ def qualified_name(self) -> str:
+ return f"{settings.CLICKHOUSE_DATABASE}.{self.table_name}"
+
+ @property
+ def run_keys_query(self) -> str:
+ """This run's keys, for embedding in an IN or NOT IN clause.
+
+ The run id is interpolated rather than passed as a parameter because these fragments end
+ up inside dictionary source queries and mutation commands, neither of which carries
+ parameters. It is a Dagster run id with the dashes replaced, so there is nothing to quote.
+ """
+ return f"SELECT {self.keys} FROM {self.qualified_name} WHERE run_id = '{self.run_id}'"
+
+ def count(self, client: Client) -> int:
+ [[count]] = client.execute(
+ f"SELECT count() FROM {self.qualified_name} WHERE run_id = %(run_id)s",
+ {"run_id": self.run_id},
+ )
+ return count
+
+ def team_ids(self, client: Client) -> 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},
+ )
+ return [row[0] for row in rows]
+
+ def distinct_key_count(self, client: Client) -> int:
+ # Deduplicated, so the number is stable whether or not a merge has collapsed the
+ # duplicate rows a retried populate leaves behind.
+ [[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},
+ )
+ return count
+
+ def sync_replica(self, client: Client) -> None:
+ client.execute(f"SYSTEM SYNC REPLICA {self.qualified_name} STRICT")
+
+ def drop_run_partition(self, client: Client) -> None:
+ # The table is partitioned by run_id, so clearing a run is a metadata-only partition drop
+ # rather than a mutation that rewrites every part. A missing partition is a no-op.
+ client.execute(
+ f"ALTER TABLE {self.qualified_name} DROP PARTITION %(run_id)s",
+ {"run_id": self.run_id},
+ )
+
+
+@dataclass(frozen=True)
+class DeletedPersonsTable(SnapshotTable):
+ """Persons whose latest ClickHouse version is deleted."""
+
+ table_name = CLEANUP_DELETED_PERSONS_TABLE
+ keys = "team_id, person_id"
+ dictionary_types = "team_id Int64, person_id UUID, max_version UInt64"
+
+ def populate(
+ self,
+ client: Client,
+ settings: Mapping[str, int] | None = None,
+ min_team_id: int = 0,
+ max_team_id: int = 0,
+ max_persons: int = 0,
+ ) -> None:
+ # A person can be soft-deleted and later revived by a higher version, so membership is
+ # decided by the latest version rather than by any version having is_deleted set. The
+ # inner IN narrows the aggregation to persons with at least one deleted version.
+ # The team filter and the LIMIT bound what one run takes on; whatever they exclude keeps
+ # its tombstones, so the next run picks it up. team_id leads the sort key, which is what
+ # lets the range prune the scan rather than only filter it.
+ team_filter = ""
+ if min_team_id:
+ team_filter += f" AND team_id >= {int(min_team_id)}"
+ if max_team_id:
+ team_filter += f" AND team_id <= {int(max_team_id)}"
+ cap = f" ORDER BY team_id, id LIMIT {int(max_persons)}" if max_persons else ""
+ client.execute(
+ f"""
+ INSERT INTO {self.qualified_name} (run_id, team_id, person_id, max_version)
+ SELECT %(run_id)s, team_id, id, max(version)
+ FROM {PERSONS_TABLE}
+ WHERE (team_id, id) IN (SELECT team_id, id FROM {PERSONS_TABLE} WHERE is_deleted > 0{team_filter}){team_filter}
+ GROUP BY team_id, id
+ HAVING argMax(is_deleted, version) > 0{cap}
+ """,
+ {"run_id": self.run_id},
+ settings=settings,
+ )
+
+
+@dataclass(frozen=True)
+class RevivedPersonsTable(SnapshotTable):
+ """Snapshotted persons that came back to life while the run was in flight.
+
+ Every dictionary below reads its source through an anti-join against this table, so recording
+ a revival here is what excludes it. That keeps the checkpoints free of mutations on the
+ snapshot tables, which would be far slower than an insert.
+ """
+
+ table_name = CLEANUP_REVIVED_PERSONS_TABLE
+ keys = "team_id, person_id"
+ dictionary_types = "team_id Int64, person_id UUID"
+
+ def populate(self, client: Client, persons: DeletedPersonsTable, settings: Mapping[str, int] | None = None) -> int:
+ # Later checkpoints re-run this, so already-recorded revivals are excluded rather than
+ # inserted again. Counting this run's rows is what reports how many are newly revived.
+ client.execute(
+ f"""
+ INSERT INTO {self.qualified_name} (run_id, team_id, person_id)
+ SELECT %(run_id)s, team_id, id
+ FROM {PERSONS_TABLE}
+ WHERE (team_id, id) IN ({persons.run_keys_query})
+ AND (team_id, id) NOT IN ({self.run_keys_query})
+ GROUP BY team_id, id
+ HAVING argMax(is_deleted, version) = 0
+ """,
+ {"run_id": self.run_id},
+ settings=settings,
+ )
+ return self.count(client)
+
+
+@dataclass(frozen=True)
+class OrphanedDistinctIdsTable(SnapshotTable):
+ """Distinct ids to remove, with the reason each one qualified.
+
+ own_tombstone records why a key is here. The exclusion at each checkpoint is re-derived from
+ live data in RevivedDistinctIdsTable rather than from this column, because both the tombstone
+ and the owner can change while the run is in flight.
+ """
+
+ table_name = CLEANUP_ORPHANED_DISTINCT_IDS_TABLE
+ keys = "team_id, distinct_id"
+ dictionary_types = "team_id Int64, distinct_id String, max_version Int64"
+
+ def populate(
+ self, client: Client, persons_dictionary: "SnapshotDictionary", settings: Mapping[str, int] | None = None
+ ) -> None:
+ # person_distinct_id2 is keyed on (team_id, distinct_id) with person_id as a value, so a
+ # distinct id can be repointed over time. Deleting rows that merely match a deleted
+ # person_id can strip the newest row and resurrect an older mapping underneath it, so the
+ # current owner is resolved with argMax and every version of a qualifying key is removed.
+ client.execute(
+ f"""
+ INSERT INTO {self.qualified_name} (run_id, team_id, distinct_id, person_id, own_tombstone, max_version)
+ SELECT
+ %(run_id)s,
+ team_id,
+ distinct_id,
+ argMax(person_id, version) AS person_id,
+ argMax(is_deleted, version) > 0 AS own_tombstone,
+ max(version) AS max_version
+ FROM {PERSON_DISTINCT_ID2_TABLE}
+ WHERE (team_id, distinct_id) IN (
+ SELECT team_id, distinct_id
+ FROM {PERSON_DISTINCT_ID2_TABLE}
+ WHERE is_deleted > 0 OR dictHas('{persons_dictionary.qualified_name}', (team_id, person_id))
+ )
+ GROUP BY team_id, distinct_id
+ HAVING own_tombstone OR dictHas('{persons_dictionary.qualified_name}', (team_id, person_id))
+ """,
+ {"run_id": self.run_id},
+ settings=settings,
+ )
+
+
+@dataclass(frozen=True)
+class RevivedDistinctIdsTable(SnapshotTable):
+ """Snapshotted distinct ids that no longer qualify for deletion.
+
+ A mapping can come back the same way a person can: ingestion re-captures a tombstoned
+ distinct id, or reset_deleted_person_distinct_ids republishes it at a higher version. The
+ snapshot froze the reason each key qualified, so without this the delete would strip every
+ version of a key that is live again, including the new row.
+ """
+
+ table_name = CLEANUP_REVIVED_DISTINCT_IDS_TABLE
+ keys = "team_id, distinct_id"
+ dictionary_types = "team_id Int64, distinct_id String"
+
+ def populate(
+ self,
+ client: Client,
+ orphaned: OrphanedDistinctIdsTable,
+ persons: DeletedPersonsTable,
+ revived: RevivedPersonsTable,
+ settings: Mapping[str, int] | None = None,
+ ) -> int:
+ # A key stops qualifying once its latest version is live AND its current owner is not a
+ # person this run is still deleting. Both arms of the original predicate have to fail.
+ client.execute(
+ f"""
+ INSERT INTO {self.qualified_name} (run_id, team_id, distinct_id)
+ SELECT %(run_id)s, team_id, distinct_id
+ FROM {PERSON_DISTINCT_ID2_TABLE}
+ WHERE (team_id, distinct_id) IN ({orphaned.run_keys_query})
+ AND (team_id, distinct_id) NOT IN ({self.run_keys_query})
+ GROUP BY team_id, distinct_id
+ HAVING argMax(is_deleted, version) = 0
+ AND (team_id, argMax(person_id, version)) NOT IN (
+ SELECT team_id, person_id FROM {persons.qualified_name}
+ WHERE run_id = '{persons.run_id}'
+ AND (team_id, person_id) NOT IN ({revived.run_keys_query})
+ )
+ """,
+ {"run_id": self.run_id},
+ settings=settings,
+ )
+ return self.count(client)
+
+
+@frozen
+class SnapshotDictionary(Dictionary):
+ """A cluster-wide dictionary over one run's rows in a worklist, minus anything since revived.
+
+ The inherited checksum hashes every declared column, which here includes max_version: the
+ delete mutation reads it from each host's local dictionary, so hosts agreeing on keys but
+ not on the version bound would delete different version sets per replica and diverge the
+ table.
+ """
+
+ source: SnapshotTable
+ # Keys recorded here are anti-joined out of the dictionary, which is how a checkpoint
+ # excludes something without mutating the worklist it came from.
+ excluded: SnapshotTable
+
+ @property
+ def key_columns(self) -> str:
+ return self.source.keys
+
+ @property
+ def name(self) -> str:
+ # Runs share the tables, so the run id has to live on the dictionary instead for two runs
+ # not to fight over one name.
+ return f"{self.source.table_name}_{self.source.run_id}_dictionary"
+
+ @property
+ def schema(self) -> str:
+ return self.source.dictionary_types
+
+ @property
+ def primary_key(self) -> str:
+ return self.key_columns
+
+ @property
+ def query(self) -> str:
+ # Aggregated because a retried populate leaves duplicate key rows until a merge collapses
+ # them, and an unaggregated read would hand the dictionary an arbitrary one. max() picks
+ # the newest bound, matching the row the sub-second version column keeps at merge time.
+ return f"""
+ SELECT {self.key_columns}, max(max_version) AS max_version
+ FROM {self.source.qualified_name}
+ WHERE run_id = '{self.source.run_id}'
+ AND ({self.key_columns}) NOT IN ({self.excluded.run_keys_query})
+ GROUP BY {self.key_columns}
+ """
+
+ @property
+ def credentials(self) -> ClickHouseCredentials:
+ # The source reads as the low-privilege dict_reader user, which falls back to the default
+ # user's credentials where dict_reader is not provisioned.
+ return get_clickhouse_creds(ClickHouseUser.DICT_READER)
+
+ def staged(self) -> StagedDictionary:
+ # A staged copy is a static object. The revival checkpoints exclude keys by reloading this
+ # dictionary so its source query re-runs against the live exclusion table, and a reload
+ # of a staged copy on another cluster would keep every revived key in the delete set.
+ # The sweep only mutates replicated tables on the cluster in hand, so it never needs one.
+ raise NotImplementedError(
+ f"{self.name} cannot be staged: its contents change during the run, and a staged copy would not"
+ )
+
+
+@dataclass(frozen=True, kw_only=True)
+class CleanupRun:
+ """Every per-run asset and setting, threaded through the ops so they execute in sequence.
+
+ Settings travel here rather than being read from config by each op, so a launch sets them in
+ one place: the first op's config. Declaring them per op would let a launch set one on some
+ ops and miss others, and a sweep whose halves disagree on dry_run or batching is worse than
+ none.
+ """
+
+ persons: DeletedPersonsTable
+ revived: RevivedPersonsTable
+ orphaned: OrphanedDistinctIdsTable
+ revived_distinct_ids: RevivedDistinctIdsTable
+ dry_run: bool
+ cleanup: bool
+ team_batches: int
+ shards: int
+ max_execution_time: int
+ max_memory_usage: int
+ dictionary_load_timeout: int
+ mutation_stall_timeout: int
+ mutation_wait_deadline: int
+ max_persons: int
+ min_team_id: int
+ max_team_id: int
+ distinct_ids_deleted_at: datetime | None = None
+ # Distinct key counts recorded when each snapshot was taken. The deletes assert against them,
+ # so a snapshot the 14-day TTL reaped mid-run fails the run instead of under-deleting silently.
+ persons_count: int = 0
+ orphaned_count: int = 0
+
+ @classmethod
+ def for_run(cls, run_id: str, config: CleanupConfig) -> "CleanupRun":
+ # Dictionary names embed the run id, and a dash is not valid in an identifier.
+ scoped = run_id.replace("-", "_")
+ return cls(
+ persons=DeletedPersonsTable(run_id=scoped),
+ revived=RevivedPersonsTable(run_id=scoped),
+ orphaned=OrphanedDistinctIdsTable(run_id=scoped),
+ revived_distinct_ids=RevivedDistinctIdsTable(run_id=scoped),
+ dry_run=config.dry_run,
+ cleanup=config.cleanup,
+ team_batches=config.team_batches,
+ 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_wait_deadline=config.mutation_wait_deadline,
+ max_persons=config.max_persons,
+ min_team_id=config.min_team_id,
+ max_team_id=config.max_team_id,
+ )
+
+ @property
+ def query_settings(self) -> dict[str, int]:
+ """Caps for the snapshot INSERT..SELECTs, which scan person and person_distinct_id2 whole.
+
+ Without these the populates run unbounded; the dictionary loads already honor the same
+ two config fields, so one launch config bounds every heavy read in the run.
+ """
+ return {"max_execution_time": self.max_execution_time, "max_memory_usage": self.max_memory_usage}
+
+ @property
+ def all_tables(self) -> tuple[SnapshotTable, ...]:
+ return (self.persons, self.revived, self.orphaned, self.revived_distinct_ids)
+
+ @property
+ def persons_dictionary(self) -> SnapshotDictionary:
+ return SnapshotDictionary(source=self.persons, excluded=self.revived, load_timeout=self.dictionary_load_timeout)
+
+ @property
+ def orphaned_dictionary(self) -> SnapshotDictionary:
+ return SnapshotDictionary(
+ source=self.orphaned, excluded=self.revived_distinct_ids, load_timeout=self.dictionary_load_timeout
+ )
+
+
+def _create_dictionary(
+ context: dagster.OpExecutionContext,
+ cluster: ClickhouseCluster,
+ dictionary: SnapshotDictionary,
+ run: CleanupRun,
+) -> SnapshotDictionary:
+ # Only the cluster in hand: the sweep's tables are replicated there and nowhere else, and
+ # SnapshotDictionary refuses staging, so a second cluster would fail here rather than diverge.
+ create_on_every_cluster(
+ context,
+ [cluster],
+ dictionary,
+ shards=run.shards,
+ max_execution_time=run.max_execution_time,
+ max_memory_usage=run.max_memory_usage,
+ )
+ load_and_verify_on_every_cluster([cluster], dictionary)
+ return dictionary
+
+
+def clear_removed_cohort_data(
+ context: dagster.OpExecutionContext,
+ config: CleanupConfig,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+) -> CleanupRun:
+ """Remove cohort membership rows for cohorts that were deleted or recalculated.
+
+ Runs ahead of the person sweep rather than after it. The sweeps cannot overlap, and the person
+ path runs for hours, so putting it last would leave cohort rows unswept whenever that path ran
+ long or failed. Going first also keeps the person snapshot as close to its own delete as
+ possible, which is what bounds how many persons can revive mid-run.
+ """
+ run = CleanupRun.for_run(context.run_id, config)
+ context.add_output_metadata({"dry_run": dagster.MetadataValue.bool(run.dry_run)})
+
+ if run.dry_run:
+ 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")})
+ # 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})
+ return run
+
+
+def snapshot_deleted_persons(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+) -> CleanupRun:
+ """Capture the persons whose latest version is deleted, tagged with this run's id."""
+ started = time.monotonic()
+ cluster.any_host_by_role(
+ partial(
+ run.persons.populate,
+ settings=run.query_settings,
+ min_team_id=run.min_team_id,
+ max_team_id=run.max_team_id,
+ max_persons=run.max_persons,
+ ),
+ NodeRole.DATA,
+ ).result()
+ # 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()
+ context.add_output_metadata(
+ {
+ "deleted_persons": dagster.MetadataValue.int(count),
+ "snapshot_seconds": dagster.MetadataValue.float(round(time.monotonic() - started, 1)),
+ }
+ )
+ return replace(run, persons_count=count)
+
+
+def snapshot_orphaned_distinct_ids(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+) -> CleanupRun:
+ """Resolve which distinct ids belong to the snapshotted persons, or tombstoned themselves."""
+ _create_dictionary(context, cluster, run.persons_dictionary, run)
+
+ started = time.monotonic()
+ cluster.any_host_by_role(
+ partial(run.orphaned.populate, persons_dictionary=run.persons_dictionary, settings=run.query_settings),
+ NodeRole.DATA,
+ ).result()
+ cluster.map_all_hosts(run.orphaned.sync_replica).result()
+ 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()
+ context.add_output_metadata(
+ {
+ "orphaned_distinct_ids": dagster.MetadataValue.int(count),
+ "snapshot_seconds": dagster.MetadataValue.float(snapshot_seconds),
+ }
+ )
+ return replace(run, orphaned_count=count)
+
+
+def recheck_revived_persons(name: str) -> dagster.OpDefinition:
+ """Build a checkpoint op that excludes any person revived since the snapshot.
+
+ The checkpoints sit at phase boundaries rather than inside the mutation, because a mutation
+ over an unpartitioned table runs long and re-checking mid-flight cannot retract work already
+ applied. A person revived inside that window has already lost its distinct id rows;
+ reset_deleted_person_distinct_ids and the sync_person_distinct_ids workflow republish them
+ from Postgres.
+ """
+
+ @dagster.op(name=name)
+ def checkpoint(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+ ) -> CleanupRun:
+ persons_before = cluster.any_host_by_role(run.revived.count, 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_total = cluster.any_host_by_role(
+ partial(
+ run.revived_distinct_ids.populate,
+ orphaned=run.orphaned,
+ persons=run.persons,
+ revived=run.revived,
+ settings=run.query_settings,
+ ),
+ NodeRole.DATA,
+ ).result()
+ cluster.map_all_hosts(run.revived_distinct_ids.sync_replica).result()
+
+ revived_persons = persons_total - persons_before
+ revived_ids = ids_total - ids_before
+ context.add_output_metadata(
+ {
+ "revived_persons": dagster.MetadataValue.int(revived_persons),
+ "revived_distinct_ids": dagster.MetadataValue.int(revived_ids),
+ }
+ )
+ if not revived_persons and not revived_ids:
+ return run
+
+ # Reloading is what applies the exclusion, so it only happens when something came back.
+ # Counted twice on purpose: the prometheus counters only surface if this pod is ever
+ # scraped, while the ClickHouse-backed counters survive the run.
+ REVIVED_PERSON_COUNTER.inc(revived_persons)
+ REVIVED_DISTINCT_ID_COUNTER.inc(revived_ids)
+ metrics = MetricsClient(cluster)
+ if revived_persons:
+ _emit(metrics, "clickhouse_cleanup_revived", {"kind": "persons"}, value=revived_persons)
+ if revived_ids:
+ _emit(metrics, "clickhouse_cleanup_revived", {"kind": "distinct_ids"}, value=revived_ids)
+ context.log.warning(
+ "%s persons and %s distinct ids came back during the run and are excluded from it",
+ revived_persons,
+ revived_ids,
+ )
+ for dictionary in (run.persons_dictionary, run.orphaned_dictionary):
+ load_and_verify_on_every_cluster([cluster], dictionary)
+ return run
+
+ return checkpoint
+
+
+def _emit(metrics: MetricsClient, name: str, labels: Mapping[str, str], value: float = 1.0) -> None:
+ """Record a counter, never letting telemetry fail the sweep."""
+ try:
+ metrics.increment(name, labels=dict(labels), value=value).result()
+ except Exception:
+ logger.warning("failed to record %s", name, exc_info=True)
+
+
+MUTATION_POLL_SECONDS = 15.0
+MUTATION_VISIBILITY_TIMEOUT_SECONDS = 300.0
+
+
+class MutationStalled(Exception):
+ pass
+
+
+@dataclass(frozen=True, kw_only=True)
+class MutationStatus:
+ """One host's view of a delete batch's mutations, read from its system.mutations."""
+
+ done: bool
+ visible: bool
+ parts_to_do: int
+ latest_fail_time: datetime | None
+ latest_fail_reason: str
+ server_now: datetime
+
+
+class MutationProgress:
+ """Decides when a polled mutation is stuck rather than merely slow or still retrying.
+
+ ClickHouse retries a failed part mutation on its own, and system.mutations keeps the
+ latest_fail_* columns populated from the newest failed attempt even after later attempts
+ succeed, so a failure reason alone is not evidence the mutation is dying. A batch is declared
+ stuck only when attempts are still failing while no part has completed for stall_timeout
+ seconds. A batch that is slow without failing is left to run: that is a big part or a busy
+ cluster, not a fault.
+
+ A failure recorded before polling began is treated as history rather than evidence, because
+ MutationRunner can re-attach to an existing mutation whose old attempts failed; only failures
+ within one stall window of the first poll, or newer than the newest one already seen, count.
+ """
+
+ def __init__(
+ self,
+ stall_timeout: float,
+ visibility_timeout: float = MUTATION_VISIBILITY_TIMEOUT_SECONDS,
+ wait_deadline: float = 0.0,
+ ) -> None:
+ self.stall_timeout = stall_timeout
+ self.visibility_timeout = visibility_timeout
+ # A mutation can be healthy and still never finish, for example blocked behind another
+ # table-sized mutation. The deadline turns that silent forever-run into a failure.
+ self.wait_deadline = wait_deadline
+ self._started_at: float | None = None
+ self._last_progress_at: float = 0.0
+ self._min_parts_to_do: int | None = None
+ self._last_fail_time: datetime | None = None
+ self._failed_since_progress = False
+
+ def observe(self, statuses: Sequence[MutationStatus], now: float) -> None:
+ """Digest one poll of every host, raising MutationStalled when the batch is stuck."""
+ first = self._started_at is None
+ if first:
+ self._started_at = now
+ self._last_progress_at = now
+ assert self._started_at is not None
+
+ if not all(status.visible for status in statuses):
+ # The mutation entry replicates through Keeper, so a lagged replica can briefly not
+ # know it yet; that only becomes a fault when it persists.
+ if now - self._started_at > self.visibility_timeout:
+ raise MutationStalled(f"not visible on every host after {self.visibility_timeout:.0f}s")
+ return
+
+ parts_to_do = sum(status.parts_to_do for status in statuses)
+ if self._min_parts_to_do is None or parts_to_do < self._min_parts_to_do:
+ self._min_parts_to_do = parts_to_do
+ self._last_progress_at = now
+ self._failed_since_progress = False
+
+ newest_fail = max((s.latest_fail_time for s in statuses if s.latest_fail_time is not None), default=None)
+ if first:
+ self._last_fail_time = newest_fail
+ if newest_fail is not None:
+ freshness_horizon = max(s.server_now for s in statuses) - timedelta(seconds=self.stall_timeout)
+ self._failed_since_progress = newest_fail > freshness_horizon
+ elif newest_fail is not None and (self._last_fail_time is None or newest_fail > self._last_fail_time):
+ self._last_fail_time = newest_fail
+ self._failed_since_progress = True
+
+ stalled_for = now - self._last_progress_at
+ if self._failed_since_progress and stalled_for > self.stall_timeout:
+ raise MutationStalled(f"attempts keep failing and no part completed in {stalled_for:.0f}s")
+
+ if self.wait_deadline and now - self._started_at > self.wait_deadline:
+ raise MutationStalled(f"not finished after {self.wait_deadline:.0f}s")
+
+
+def _wait_for_mutation(
+ context: dagster.OpExecutionContext,
+ cluster: ClickhouseCluster,
+ table: str,
+ mutation: MutationWaiter,
+ label: str,
+ stall_timeout: float,
+ wait_deadline: float,
+) -> None:
+ """Block until the mutation finishes on every host, failing only when it is stuck.
+
+ MutationWaiter.wait polls is_done forever and never reads latest_fail_reason, so a mutation
+ failing on every attempt is indistinguishable from a slow one. MutationProgress arbitrates
+ between the two, and the raised Failure names the batch and mutation ids for diagnosis.
+
+ Every host is polled, not one: a mutation can fail on a single replica, and asking only one
+ host would poll a stuck mutation forever.
+ """
+ ids = tuple(mutation.mutation_ids)
+
+ def status(client: Client) -> MutationStatus:
+ [[done, visible, parts_to_do, fail_time, fail_reason, server_now]] = client.execute(
+ """
+ SELECT
+ countIf(is_done) = count() AND count() = %(expected)s,
+ count() = %(expected)s,
+ sum(parts_to_do),
+ max(latest_fail_time),
+ argMax(latest_fail_reason, latest_fail_time),
+ now()
+ FROM system.mutations
+ WHERE database = %(database)s AND table = %(table)s AND mutation_id IN %(ids)s
+ """,
+ {"database": settings.CLICKHOUSE_DATABASE, "table": table, "ids": ids, "expected": len(ids)},
+ )
+ return MutationStatus(
+ done=bool(done),
+ visible=bool(visible),
+ parts_to_do=int(parts_to_do or 0),
+ # latest_fail_time is the epoch when no attempt ever failed, so the reason is the
+ # authoritative "has failed" signal and the time is only meaningful alongside it.
+ latest_fail_time=fail_time if fail_reason else None,
+ latest_fail_reason=fail_reason or "",
+ server_now=server_now,
+ )
+
+ progress = MutationProgress(stall_timeout=stall_timeout, wait_deadline=wait_deadline)
+ while True:
+ statuses = list(cluster.map_all_hosts(status).result().values())
+ if statuses and all(s.done for s in statuses):
+ return
+
+ parts_to_do = sum(s.parts_to_do for s in statuses)
+ fail_reason = next((s.latest_fail_reason for s in statuses if s.latest_fail_reason), "")
+ try:
+ progress.observe(statuses, time.monotonic())
+ except MutationStalled as stalled:
+ raise dagster.Failure(
+ description=f"mutation on {table} looks stuck: {fail_reason or stalled}",
+ metadata={
+ "batch": dagster.MetadataValue.text(label),
+ "mutation_ids": dagster.MetadataValue.text(", ".join(ids)),
+ "parts_to_do": dagster.MetadataValue.int(parts_to_do),
+ "latest_fail_reason": dagster.MetadataValue.text(fail_reason),
+ "stall": dagster.MetadataValue.text(str(stalled)),
+ },
+ ) from stalled
+
+ if fail_reason:
+ context.log.warning(
+ "%s: %s parts remaining, ClickHouse retrying after: %s", label, parts_to_do, fail_reason
+ )
+ else:
+ context.log.info("%s: %s parts remaining", label, parts_to_do)
+ time.sleep(MUTATION_POLL_SECONDS)
+
+
+@dataclass(frozen=True, kw_only=True)
+class TeamRange:
+ """One inclusive [low, high] slice of the candidate team ids."""
+
+ low: int
+ high: int
+
+
+def _team_ranges(team_ids: list[int], batches: int) -> list[TeamRange]:
+ """Cut sorted team ids into contiguous, inclusive [low, high] ranges that cover all of them.
+
+ Bounds are real team ids rather than an even split of the id space, so batches hold roughly
+ equal numbers of teams however sparsely the ids are distributed. They are also literal
+ integers, which keeps each batch's mutation command text short and identical across reruns —
+ that is what lets MutationRunner re-attach to a batch instead of reissuing it.
+ """
+ if not team_ids:
+ return []
+ ordered = sorted(team_ids)
+ size = max(1, ceil(len(ordered) / max(1, batches)))
+ return [
+ TeamRange(low=chunk[0], high=chunk[-1])
+ for chunk in (ordered[i : i + size] for i in range(0, len(ordered), size))
+ ]
+
+
+def _run_ordered_delete(
+ context: dagster.OpExecutionContext,
+ cluster: ClickhouseCluster,
+ table: str,
+ dictionary: SnapshotDictionary,
+ key_tuple: str,
+ team_ranges: list[TeamRange],
+ metrics: MetricsClient,
+ stall_timeout: float,
+ wait_deadline: float,
+) -> int:
+ """Delete every snapshotted row from `table`, oldest version first.
+
+ Two passes per team range, in this order and never merged:
+
+ A. every version below the key's snapshot max
+ B. the max itself
+
+ Pass A can never remove the tombstone, so while it runs the surviving max for each key is
+ still the tombstone and readers keep resolving the key as deleted. Only once A has finished
+ for a range does B remove the last row, and by then there is no older version left to fall
+ back to. Doing this in one pass instead would let an interrupted mutation strip the tombstone
+ from a part while an older live row survived in another, handing the key back to a person
+ this run is about to delete.
+
+ Both passes are bounded by the snapshot's max_version, so rows written after the snapshot are
+ never touched by a run that did not observe them.
+ """
+ lookup = f"dictGetOrNull({dictionary.qualified_name!r}, 'max_version', {key_tuple}) as snapshot_max"
+ passes = (
+ ("below_max", f"isNotNull({lookup}) AND version < snapshot_max"),
+ ("max", f"isNotNull({lookup}) AND version <= snapshot_max"),
+ )
+
+ batches = 0
+ for team_range in team_ranges:
+ for pass_name, key_predicate in passes:
+ 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),
+ )
+ # Both tables are replicated and not sharded, so a mutation started on one host
+ # reaches all of them.
+ mutation = cluster.any_host(runner).result()
+ _wait_for_mutation(
+ context,
+ cluster,
+ table,
+ mutation,
+ f"{table}:{team_range.low}-{team_range.high}:{pass_name}",
+ stall_timeout,
+ wait_deadline,
+ )
+ _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
+
+
+def _require_snapshot_intact(cluster: ClickhouseCluster, table: SnapshotTable, recorded: 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()
+ if current != recorded:
+ raise dagster.Failure(
+ f"{table.table_name} holds {current} keys for this run but {recorded} were snapshotted;"
+ " the snapshot TTL has likely expired mid-run, so re-run from a fresh snapshot"
+ )
+
+
+def delete_orphaned_distinct_ids(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+) -> CleanupRun:
+ """Remove every version of the qualifying distinct id mappings, oldest version first."""
+ if run.dry_run:
+ 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))})
+
+ _run_ordered_delete(
+ context,
+ cluster,
+ PERSON_DISTINCT_ID2_TABLE,
+ run.orphaned_dictionary,
+ "(team_id, distinct_id)",
+ ranges,
+ MetricsClient(cluster),
+ run.mutation_stall_timeout,
+ run.mutation_wait_deadline,
+ )
+
+ return replace(run, distinct_ids_deleted_at=datetime.now(UTC))
+
+
+def persist_deleted_persons(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ persons_database: dagster.ResourceParam[psycopg2.extensions.connection],
+ run: CleanupRun,
+) -> CleanupRun:
+ """Hand the swept persons to Postgres, before the step that makes them unrecoverable.
+
+ The queue is advisory, never authoritative. Rows sit here until the drain runs, so a person
+ can be revived after being queued no matter how carefully this op checks. ClickHouse also
+ trails Postgres, so a person revived in Postgres can still read as deleted here. The drain
+ has to re-verify each person against Postgres before deleting it.
+ """
+ if run.dry_run:
+ context.log.info("dry run: skipping the write to %s", PG_CLEANUP_QUEUE_TABLE)
+ return run
+
+ def read_page(client: Client, after: tuple[int, str] | None) -> list[tuple[int, str]]:
+ # Reads the snapshot directly rather than the dictionary's query, so adding attributes to
+ # the dictionary cannot silently change the shape of what gets queued. Keyset pagination
+ # over (team_id, person_id) follows the table's sort key, and DISTINCT collapses the
+ # duplicate versions a retried snapshot insert can leave in the ReplacingMergeTree.
+ page_filter = "AND (team_id, person_id) > (%(after_team)s, toUUID(%(after_person)s))" if after else ""
+ return client.execute(
+ f"""
+ SELECT DISTINCT team_id, person_id FROM {run.persons.qualified_name}
+ WHERE run_id = %(run_id)s
+ AND (team_id, person_id) NOT IN ({run.revived.run_keys_query})
+ {page_filter}
+ ORDER BY team_id, person_id
+ LIMIT %(limit)s
+ """,
+ {
+ "run_id": run.persons.run_id,
+ "limit": PERSIST_PAGE_SIZE,
+ "after_team": after[0] if after else 0,
+ "after_person": after[1] if after else "",
+ },
+ settings=run.query_settings,
+ )
+
+ deleted_at = run.distinct_ids_deleted_at
+ written = 0
+ after: tuple[int, str] | None = None
+ with persons_database.cursor() as cursor:
+ cursor.execute("SET application_name = 'clickhouse_cleanup'")
+ # Bounded so a lock conflict on the queue fails the page instead of holding a transaction
+ # open on the persons writer; the per-page upsert is idempotent, so a retry is safe.
+ cursor.execute("SET statement_timeout = '120s'")
+ cursor.execute("SET lock_timeout = '10s'")
+ while True:
+ page = cluster.any_host_by_role(partial(read_page, after=after), NodeRole.DATA).result()
+ if not page:
+ break
+ # A person can be deleted, drained, re-created and deleted again under the same uuid,
+ # and the drain only looks at rows where cleaned_at is null. Leaving an already-cleaned
+ # row untouched would drop that second deletion on the floor and leak its Postgres rows
+ # for good, so the conflict re-arms the row instead of ignoring it. The WHERE keeps a
+ # retried op from rewriting rows that already hold these values: an unconditional
+ # DO UPDATE writes a new tuple version per row, so a retry over millions of rows would
+ # leave that many dead tuples for the persons writer to vacuum.
+ execute_values(
+ cursor,
+ f"""
+ INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at)
+ VALUES %s
+ ON CONFLICT (team_id, person_uuid) DO UPDATE
+ SET deleted_at = EXCLUDED.deleted_at, cleaned_at = NULL
+ WHERE {PG_CLEANUP_QUEUE_TABLE}.cleaned_at IS NOT NULL
+ OR {PG_CLEANUP_QUEUE_TABLE}.deleted_at IS DISTINCT FROM EXCLUDED.deleted_at
+ """,
+ [(team_id, str(person_id), deleted_at) for team_id, person_id in page],
+ page_size=1000,
+ )
+ # The conflict guard makes rowcount "rows changed", not "rows queued"; the metric is
+ # the queued set, which is the page.
+ written += len(page)
+ # Commit per page: the upsert makes replays idempotent, and one transaction across
+ # millions of rows would hold WAL and xmin on the persons writer for the whole op.
+ persons_database.commit()
+ if len(page) < PERSIST_PAGE_SIZE:
+ break
+ last_team, last_person = page[-1]
+ after = (last_team, str(last_person))
+
+ context.add_output_metadata({"queued_for_postgres": dagster.MetadataValue.int(written)})
+ return run
+
+
+def delete_persons(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+) -> CleanupRun:
+ """Remove the snapshotted persons from the ClickHouse person table, oldest version first.
+
+ `person` carries the same tombstone-on-top-of-live-versions shape as person_distinct_id2, so
+ it has the same resurrection hazard and gets the same two ordered passes.
+ """
+ if run.dry_run:
+ 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))})
+
+ _run_ordered_delete(
+ context,
+ cluster,
+ PERSONS_TABLE,
+ run.persons_dictionary,
+ "(team_id, id)",
+ ranges,
+ MetricsClient(cluster),
+ run.mutation_stall_timeout,
+ run.mutation_wait_deadline,
+ )
+
+ return run
+
+
+def drop_snapshot_assets(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ run: CleanupRun,
+) -> None:
+ """Drop this run's dictionaries and clear the rows they read."""
+ if not run.cleanup:
+ context.log.info("cleanup disabled, leaving the assets for run %s in place", run.persons.run_id)
+ return
+
+ # The dictionaries read from the tables, so they have to go first.
+ for dictionary in (run.orphaned_dictionary, run.persons_dictionary):
+ cluster.map_all_hosts(dictionary.drop).result()
+ # The TTL would reap these anyway. Clearing them now keeps the shared tables small enough that
+ # a run's own rows stay cheap to read.
+ for table in run.all_tables:
+ cluster.any_host_by_role(table.drop_run_partition, NodeRole.DATA).result()
+
+
[email protected]_hook(required_resource_keys={"cluster"})
+def drop_assets_on_failure(context: dagster.HookContext) -> None:
+ """Drop this run's dictionaries when an op fails.
+
+ Dagster skips downstream ops after a failure, so drop_snapshot_assets never runs and the
+ dictionaries would survive on the cluster and accumulate across failures. Their names come
+ from the run id alone, so this needs nothing from the failed op.
+
+ This ignores the cleanup flag on purpose. A stranded dictionary holds its whole key set in
+ memory on every host, which costs more than the ability to inspect it after a failure.
+
+ The failed run's rows are left behind deliberately. They cost far less than a dictionary and
+ the tables' TTL reaps them, so a failed sweep stays inspectable in the meantime.
+ """
+ run_id = context.run_id.replace("-", "_")
+ cluster = context.resources.cluster
+
+ # A mutation still reading one of these dictionaries would fail the moment it is dropped, so
+ # kill this run's mutations first. Killing a half-applied ordered delete is safe: every
+ # intermediate state leaves each key's tombstone as the surviving max version, so nothing
+ # resurrects. Only mutations naming this run's dictionaries are touched.
+ def kill_run_mutations(client: Client) -> None:
+ for table in (PERSON_DISTINCT_ID2_TABLE, PERSONS_TABLE):
+ client.execute(
+ f"KILL MUTATION WHERE database = %(database)s AND table = %(table)s"
+ f" AND NOT is_done AND command LIKE %(pattern)s SYNC",
+ {
+ "database": settings.CLICKHOUSE_DATABASE,
+ "table": table,
+ "pattern": f"%_{run_id}_dictionary%",
+ },
+ )
+
+ cluster.map_all_hosts(kill_run_mutations).result()
+
+ for table_name in CLEANUP_SNAPSHOT_TABLES:
+ name = f"{settings.CLICKHOUSE_DATABASE}.{table_name}_{run_id}_dictionary"
+ cluster.map_all_hosts(lambda client, n=name: client.execute(f"DROP DICTIONARY IF EXISTS {n} SYNC")).result()
+
+
[email protected](hooks={drop_assets_on_failure}, tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
+def clickhouse_deletion_sweep_job():
+ """Sweep deleted cohort memberships, then deleted persons and their distinct ids."""
+ run = snapshot_orphaned_distinct_ids(snapshot_deleted_persons(clear_removed_cohort_data()))
+
+ run = recheck_revived_persons("recheck_before_distinct_id_delete")(run)
+ run = delete_orphaned_distinct_ids(run)
+
+ # One checkpoint covers both the handoff and the person delete, so they agree on who is
+ # deleted. Checking again between them would let a revival spare a person in ClickHouse
+ # while its row stayed queued, and the Postgres drain would then clear a live person.
+ run = recheck_revived_persons("recheck_before_person_delete")(run)
+ run = persist_deleted_persons(run)
+
+ # Each op takes the previous op's output, which is what keeps the sweeps in sequence.
+ drop_snapshot_assets(delete_persons(run))
diff --git a/posthog/dags/common/dictionaries.py b/posthog/dags/common/dictionaries.py
new file mode 100644
index 000000000000..6d6fed4af073
--- /dev/null
+++ b/posthog/dags/common/dictionaries.py
@@ -0,0 +1,167 @@
+"""One ClickHouse dictionary definition, created on every host and loaded until they all agree.
+
+Every dictionary-driven deletion job builds the same thing: a dictionary over a small worklist
+table, created on each host, loaded, and checksummed so every host is proven to hold the same
+rows before a mutation joins it. Subclasses supply the identity (name, columns, key, source
+query, credentials); this base owns the lifecycle so there is one implementation of create,
+load-with-deadline, checksum and drop.
+
+Staging across clusters (``staged``) is declared here because ``staged_dictionary`` needs it on
+every dictionary it can carry. A subclass whose contents change during a run must refuse it: a
+staged copy is a static object, so a reload on the far cluster would not see the change.
+"""
+
+import abc
+import time
+
+from django.conf import settings
+
+from clickhouse_driver.client import Client
+
+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, get_clickhouse_creds
+from posthog.dags.common.staged_dictionary import StagedDictionary
+from posthog.dataclasses import frozen
+
+# A dictionary wedged in LOADING would otherwise hold a run open forever and silently: a run that
+# hangs raises no failure alert, while one that times out does.
+DEFAULT_DICTIONARY_LOAD_TIMEOUT: float = 1800.0
+
+
+@frozen
+class Dictionary(abc.ABC):
+ load_timeout: float = DEFAULT_DICTIONARY_LOAD_TIMEOUT
+
+ @property
+ @abc.abstractmethod
+ def name(self) -> str:
+ """Unqualified dictionary name; the subclass owns the naming scheme."""
+
+ @property
+ @abc.abstractmethod
+ def schema(self) -> str:
+ """Column declarations, e.g. ``team_id Int64, key String``."""
+
+ @property
+ @abc.abstractmethod
+ def primary_key(self) -> str:
+ """Comma-separated key columns."""
+
+ @property
+ @abc.abstractmethod
+ def query(self) -> str:
+ """The SELECT the dictionary source runs against ClickHouse."""
+
+ @abc.abstractmethod
+ def staged(self) -> StagedDictionary:
+ """Where this dictionary's rows go so another cluster can load them; see StagedDictionary.
+
+ Keyed by the dictionary's own name, never by anything per-run. A dictionary outlives the
+ run that created it, and CREATE ... IF NOT EXISTS keys on that same name, so a per-run key
+ would leave the earlier definition pointing at an object no later run writes.
+ """
+
+ @property
+ def credentials(self) -> ClickHouseCredentials:
+ """Credentials the dictionary source reads as.
+
+ Defaults to the default user. Override only when the role's SELECT grants on the source
+ tables are known to exist in every environment; grants live in infra, not this repo.
+ """
+ return get_clickhouse_creds(ClickHouseUser.DEFAULT)
+
+ @property
+ def qualified_name(self) -> str:
+ return f"{settings.CLICKHOUSE_DATABASE}.{self.name}"
+
+ def create(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
+ """``query`` overrides the SOURCE query, for a host that cannot see the source table."""
+ # Credentials are query parameters so they stay out of the traced statement.
+ creds = self.credentials
+ client.execute(
+ f"""
+ CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} ({self.schema})
+ PRIMARY KEY {self.primary_key}
+ SOURCE(CLICKHOUSE(DB %(database)s USER %(user)s PASSWORD %(password)s QUERY %(query)s))
+ LAYOUT(COMPLEX_KEY_HASHED(SHARDS {shards}))
+ LIFETIME(0)
+ SETTINGS(max_execution_time={max_execution_time}, max_memory_usage={max_memory_usage})
+ """,
+ {
+ "database": settings.CLICKHOUSE_DATABASE,
+ "user": creds.user,
+ "password": creds.password,
+ "query": query or self.query,
+ },
+ )
+
+ def recreate(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
+ """Replace the dictionary, so no definition an earlier run left behind can survive.
+
+ CREATE ... IF NOT EXISTS keeps the existing source, which is right where that source is the
+ replicated table and wrong where it is a staged object whose query can change between
+ deploys.
+ """
+ self.drop(client)
+ self.create(client, shards, max_execution_time, max_memory_usage, query)
+
+ def exists(self, client: Client) -> bool:
+ [[count]] = client.execute(
+ "SELECT count() FROM system.dictionaries WHERE database = %(database)s AND name = %(name)s",
+ {"database": settings.CLICKHOUSE_DATABASE, "name": self.name},
+ )
+ return count > 0
+
+ def drop(self, client: Client) -> None:
+ client.execute(f"DROP DICTIONARY IF EXISTS {self.qualified_name} SYNC")
+
+ def is_loaded(self, client: Client) -> bool:
+ results = client.execute(
+ "SELECT status, last_exception FROM system.dictionaries WHERE database = %(database)s AND name = %(name)s",
+ {"database": settings.CLICKHOUSE_DATABASE, "name": self.name},
+ )
+ if not results:
+ raise Exception(f"{self.qualified_name} does not exist")
+ [[status, last_exception]] = results
+ if status == "LOADED":
+ return True
+ if status in {"LOADING", "FAILED_AND_RELOADING", "LOADED_AND_RELOADING"}:
+ return False
+ if status == "FAILED":
+ raise Exception(f"{self.qualified_name} failed to load: {last_exception}")
+ raise Exception(f"{self.qualified_name} in unexpected status: {status}")
+
+ def load(self, client: Client) -> int:
+ """Reload on this host, wait for it to finish within ``load_timeout``, and return the checksum."""
+ client.execute(f"SYSTEM RELOAD DICTIONARY {self.qualified_name}")
+
+ # The reload is asynchronous, so a consumer would read a half-populated dictionary
+ # without this wait.
+ deadline = time.monotonic() + self.load_timeout
+ while not self.is_loaded(client):
+ if time.monotonic() > deadline:
+ raise Exception(f"{self.qualified_name} still not loaded after {self.load_timeout:.0f}s")
+ time.sleep(5.0)
+
+ return self.checksum(client)
+
+ def checksum(self, client: Client) -> int:
+ # XOR of per-row hashes is order independent, so hosts holding the same entries agree
+ # regardless of read order and no sort is needed. cityHash64(*) covers every declared
+ # column, attributes included: a consumer reads attributes from whichever host it lands
+ # on, so hosts must agree on more than the key set.
+ [[checksum]] = client.execute(f"SELECT groupBitXor(cityHash64(*)) FROM {self.qualified_name}")
+ return checksum
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 41580c3d5776..53c207805371 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -1,5 +1,4 @@
import abc
-import time
import uuid
from collections.abc import Callable
from dataclasses import dataclass
@@ -27,6 +26,7 @@ from posthog.clickhouse.cluster import (
)
from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLE
from posthog.dags.common import JobOwners
+from posthog.dags.common.dictionaries import Dictionary
from posthog.dags.common.staged_dictionary import (
StagedDictionary,
create_on_every_cluster,
@@ -73,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.",
)
+ dictionary_load_timeout: int = pydantic.Field(
+ default=1800,
+ description="The maximum number of seconds to wait for a dictionary to finish loading on a host before "
+ "failing the run. A dictionary wedged in LOADING would otherwise hold the run open forever without "
+ "raising any failure alert.",
+ )
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 "
@@ -256,109 +262,20 @@ class AdhocEventDeletesTable(Table):
@frozen
-class Dictionary(abc.ABC):
- source: Table
+class PendingDeletesDictionary(Dictionary):
+ source: PendingDeletesTable
@property
def name(self) -> str:
return f"{self.source.table_name}_dictionary"
@property
- def qualified_name(self):
- return f"{settings.CLICKHOUSE_DATABASE}.{self.name}"
+ def schema(self) -> str:
+ return "team_id Int64, deletion_type UInt8, key String, created_at DateTime"
@property
- @abc.abstractmethod
- def query(self) -> str:
- raise NotImplementedError()
-
- @abc.abstractmethod
- def create(
- self,
- client: Client,
- shards: int,
- max_execution_time: int,
- max_memory_usage: int,
- query: str | None = None,
- ) -> None:
- """``query`` overrides the SOURCE query, for a host that cannot see the source table."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def staged(self) -> StagedDictionary:
- """Where this dictionary's rows go so another cluster can load them; see StagedDictionary.
-
- Keyed by the dictionary's own name, never by anything per-run. A dictionary outlives the
- run that created it, and CREATE ... IF NOT EXISTS keys on that same name, so a per-run key
- would leave the earlier definition pointing at an object no later run writes.
- """
- raise NotImplementedError()
-
- def recreate(
- self,
- client: Client,
- shards: int,
- max_execution_time: int,
- max_memory_usage: int,
- query: str | None = None,
- ) -> None:
- """Replace the dictionary, so no definition an earlier run left behind can survive.
-
- CREATE ... IF NOT EXISTS keeps the existing source, which is right where that source is the
- replicated table and wrong where it is a staged object whose query can change between
- deploys.
- """
- self.drop(client)
- self.create(client, shards, max_execution_time, max_memory_usage, query)
-
- def exists(self, client: Client) -> bool:
- results = client.execute(
- "SELECT count() FROM system.dictionaries WHERE database = %(database)s AND name = %(name)s",
- {"database": settings.CLICKHOUSE_DATABASE, "name": self.name},
- )
- [[count]] = results
- return count > 0
-
- def drop(self, client: Client) -> None:
- client.execute(f"DROP DICTIONARY IF EXISTS {self.qualified_name} SYNC")
-
- def __is_loaded(self, client: Client) -> bool:
- results = client.execute(
- "SELECT status, last_exception FROM system.dictionaries WHERE database = %(database)s AND name = %(name)s",
- {"database": settings.CLICKHOUSE_DATABASE, "name": self.name},
- )
- if not results:
- raise Exception("dictionary does not exist")
- else:
- [[status, last_exception]] = results
- if status == "LOADED":
- return True
- elif status in {"LOADING", "FAILED_AND_RELOADING", "LOADED_AND_RELOADING"}:
- return False
- elif status == "FAILED":
- raise Exception(f"failed to load: {last_exception}")
- else:
- raise Exception(f"unexpected status: {status}")
-
- def load(self, client: Client):
- # TODO: this should probably not reload if the dictionary is already loaded
- client.execute(f"SYSTEM RELOAD DICTIONARY {self.qualified_name}")
-
- # reload is async, so we need to wait for the dictionary to actually be loaded
- # TODO: this should probably throw on unexpected reloads
- while not self.__is_loaded(client):
- time.sleep(5.0)
-
- return self.checksum(client)
-
- @abc.abstractmethod
- def checksum(self, client: Client) -> int:
- raise NotImplementedError()
-
-
-@frozen
-class PendingDeletesDictionary(Dictionary):
- source: PendingDeletesTable
+ def primary_key(self) -> str:
+ return "team_id, deletion_type, key"
@property
def query(self) -> str:
@@ -368,54 +285,26 @@ class PendingDeletesDictionary(Dictionary):
return StagedDictionary(
key=f"{self.name}.parquet",
columns="team_id, deletion_type, key, created_at",
- structure="team_id Int64, deletion_type UInt8, key String, created_at DateTime",
- )
-
- def create(
- self,
- client: Client,
- shards: int,
- max_execution_time: int,
- max_memory_usage: int,
- query: str | None = None,
- ) -> None:
- client.execute(
- f"""
- CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (
- team_id Int64,
- deletion_type UInt8,
- key String,
- created_at DateTime,
- )
- PRIMARY KEY team_id, deletion_type, key
- SOURCE(CLICKHOUSE(DB %(database)s USER %(user)s PASSWORD %(password)s QUERY %(query)s))
- LAYOUT(COMPLEX_KEY_HASHED(SHARDS {shards}))
- LIFETIME(0)
- SETTINGS(max_execution_time={max_execution_time}, max_memory_usage={max_memory_usage})
- """,
- {
- "database": settings.CLICKHOUSE_DATABASE,
- "user": settings.CLICKHOUSE_USER,
- "password": settings.CLICKHOUSE_PASSWORD,
- "query": query or self.query,
- },
- )
-
- def checksum(self, client: Client) -> int:
- results = client.execute(
- f"""
- SELECT groupBitXor(row_checksum) AS table_checksum
- FROM (SELECT cityHash64(*) AS row_checksum FROM {self.qualified_name} ORDER BY team_id, key)
- """
+ structure=self.schema,
)
- [[checksum]] = results
- return checksum
@frozen
class AdhocEventDeletesDictionary(Dictionary):
source: AdhocEventDeletesTable
+ @property
+ def name(self) -> str:
+ return f"{self.source.table_name}_dictionary"
+
+ @property
+ def schema(self) -> str:
+ return "team_id Int64, uuid UUID, created_at DateTime64(6, 'UTC')"
+
+ @property
+ def primary_key(self) -> str:
+ return "team_id, uuid"
+
@property
def query(self) -> str:
return f"SELECT team_id, uuid, created_at FROM {self.source.qualified_name} WHERE (team_id, uuid) not in (SELECT team_id, uuid FROM {self.source.qualified_name} WHERE is_deleted = 1)"
@@ -424,47 +313,8 @@ class AdhocEventDeletesDictionary(Dictionary):
return StagedDictionary(
key=f"{self.name}.parquet",
columns="team_id, uuid, created_at",
- structure="team_id Int64, uuid UUID, created_at DateTime64(6, 'UTC')",
- )
-
- def create(
- self,
- client: Client,
- shards: int,
- max_execution_time: int,
- max_memory_usage: int,
- query: str | None = None,
- ) -> None:
- client.execute(
- f"""
- CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (
- team_id Int64,
- uuid UUID,
- created_at DateTime64(6, 'UTC')
- )
- PRIMARY KEY team_id, uuid
- SOURCE(CLICKHOUSE(DB %(database)s USER %(user)s PASSWORD %(password)s QUERY %(query)s))
- LAYOUT(COMPLEX_KEY_HASHED(SHARDS {shards}))
- LIFETIME(0)
- SETTINGS(max_execution_time={max_execution_time}, max_memory_usage={max_memory_usage})
- """,
- {
- "database": settings.CLICKHOUSE_DATABASE,
- "user": settings.CLICKHOUSE_USER,
- "password": settings.CLICKHOUSE_PASSWORD,
- "query": query or self.query,
- },
- )
-
- def checksum(self, client: Client) -> int:
- results = client.execute(
- f"""
- SELECT groupBitXor(row_checksum) AS table_checksum
- FROM (SELECT cityHash64(*) AS row_checksum FROM {self.qualified_name} ORDER BY team_id, uuid)
- """
+ structure=self.schema,
)
- [[checksum]] = results
- return checksum
@dagster.op
@@ -566,6 +416,7 @@ def create_deletes_dict(
del_dict = PendingDeletesDictionary(
source=load_pending_deletions,
+ load_timeout=config.dictionary_load_timeout,
)
create_on_every_cluster(
@@ -597,6 +448,7 @@ def create_adhoc_event_deletes_dict(
del_dict = AdhocEventDeletesDictionary(
source=adhoc_event_deletions,
+ load_timeout=config.dictionary_load_timeout,
)
create_on_every_cluster(
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index 64f6ea0fda20..d25de83685dc 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -5,6 +5,7 @@ from posthog.dags import (
backfill_materialized_column,
backups,
ch_examples,
+ clickhouse_cleanup,
create_materialized_column,
data_deletion_requests,
deletes,
@@ -33,6 +34,7 @@ defs = dagster.Definitions(
],
jobs=[
add_index_to_materialized_column.add_index_to_materialized_column,
+ clickhouse_cleanup.clickhouse_deletion_sweep_job,
create_materialized_column.create_materialized_column,
drop_materialized_column.drop_materialized_column,
deletes.deletes_job,
diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.py
new file mode 100644
index 000000000000..4a695b4609b1
--- /dev/null
+++ b/posthog/dags/tests/test_clickhouse_cleanup.py
@@ -0,0 +1,893 @@
+import itertools
+from collections.abc import Iterator
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+from functools import partial
+from uuid import UUID
+
+import pytest
+from unittest.mock import patch
+
+import dagster
+import psycopg2
+from clickhouse_driver import Client
+
+from posthog.clickhouse.cleanup_snapshots import (
+ CLEANUP_DELETED_PERSONS_TABLE,
+ CLEANUP_ORPHANED_DISTINCT_IDS_TABLE,
+ CLEANUP_REVIVED_DISTINCT_IDS_TABLE,
+ CLEANUP_REVIVED_PERSONS_TABLE,
+ CLEANUP_SNAPSHOT_TABLES,
+)
+from posthog.clickhouse.cluster import ClickhouseCluster
+from posthog.dags import clickhouse_cleanup
+from posthog.dags.clickhouse_cleanup import (
+ PG_CLEANUP_QUEUE_TABLE,
+ MutationProgress,
+ MutationStalled,
+ MutationStatus,
+ OrphanedDistinctIdsTable,
+ clickhouse_deletion_sweep_job,
+)
+from posthog.models.async_deletion import AsyncDeletion, DeletionType
+from posthog.models.person.util import create_person, create_person_distinct_id
+from posthog.persons_db import persons_db_url
+
+TEAM_ID = 4242
+COHORT_ID = 77
+
+# dry_run defaults to true, so a real sweep opts in. Declared on the first op alone, which is
+# what stops a launch from setting it on one op and missing another.
+RUN_FOR_REAL = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False}}}}
+
+
+def persons_database() -> Iterator[psycopg2.extensions.connection]:
+ conn = psycopg2.connect(persons_db_url(writer=True))
+ try:
+ with conn.cursor() as cursor:
+ cursor.execute(f"TRUNCATE {PG_CLEANUP_QUEUE_TABLE}")
+ conn.commit()
+ yield conn
+ finally:
+ conn.close()
+
+
+def run_job(cluster: ClickhouseCluster, persons_database, run_config=RUN_FOR_REAL, raise_on_error=True):
+ return clickhouse_deletion_sweep_job.execute_in_process(
+ run_config=run_config,
+ resources={"cluster": cluster, "persons_database": persons_database},
+ raise_on_error=raise_on_error,
+ )
+
+
+def visible_persons(client: Client) -> int:
+ # SELECT hides lightweight-deleted rows, so this counts what survived the sweep.
+ [[count]] = client.execute("SELECT count() FROM person WHERE team_id = %(team_id)s", {"team_id": TEAM_ID})
+ return count
+
+
+def current_persons(client: Client) -> int:
+ [[count]] = client.execute("SELECT count() FROM person FINAL WHERE team_id = %(team_id)s", {"team_id": TEAM_ID})
+ return count
+
+
+def rows_for(person_uuid: str):
+ # Raw row count, so it sees every surviving version rather than the collapsed one.
+ def query(client: Client) -> int:
+ [[count]] = client.execute(
+ "SELECT count() FROM person WHERE team_id = %(team_id)s AND id = %(id)s",
+ {"team_id": TEAM_ID, "id": person_uuid},
+ )
+ return count
+
+ return query
+
+
+def surviving_distinct_ids(client: Client) -> set[str]:
+ rows = client.execute(
+ "SELECT DISTINCT distinct_id FROM person_distinct_id2 WHERE team_id = %(team_id)s", {"team_id": TEAM_ID}
+ )
+ return {row[0] for row in rows}
+
+
+def current_owner(distinct_id: str):
+ def query(client: Client) -> UUID | None:
+ rows = client.execute(
+ """
+ SELECT argMax(person_id, version)
+ FROM person_distinct_id2
+ WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s
+ GROUP BY distinct_id
+ """,
+ {"team_id": TEAM_ID, "distinct_id": distinct_id},
+ )
+ return rows[0][0] if rows else None
+
+ return query
+
+
+def cohort_rows(client: Client) -> int:
+ [[count]] = client.execute("SELECT count() FROM cohortpeople WHERE team_id = %(team_id)s", {"team_id": TEAM_ID})
+ return count
+
+
+def dictionaries_for_run(run_id: str):
+ """Count only this run's dictionaries.
+
+ Scoped to the run rather than the table prefixes, so the assertion cannot be thrown off by
+ leftovers another test or an earlier session left in the shared dev database.
+ """
+ suffix = f"%{run_id.replace('-', '_')}%"
+
+ def query(client: Client) -> int:
+ [[dictionaries]] = client.execute(
+ "SELECT count() FROM system.dictionaries WHERE name LIKE %(suffix)s", {"suffix": suffix}
+ )
+ return dictionaries
+
+ return query
+
+
+def snapshot_rows_for_run(run_id: str):
+ """Count this run's rows across every snapshot table.
+
+ The tables are created by migration and outlive every run, so what a run has to clean up is
+ its rows rather than the tables. Anchored to the constants, not to literals that can drift out
+ of step with a rename.
+ """
+ scoped = run_id.replace("-", "_")
+
+ def query(client: Client) -> int:
+ return sum(
+ client.execute(
+ f"SELECT count() FROM {table} WHERE run_id = %(run_id)s",
+ {"run_id": scoped},
+ )[0][0]
+ for table in CLEANUP_SNAPSHOT_TABLES
+ )
+
+ return query
+
+
+DECOY_RUN_ID = "decoy_run"
+
+
+def seed_decoy_run(cluster: ClickhouseCluster, spared_person: str, spared_distinct_id: str, doomed_person: str) -> None:
+ """Fill every snapshot table with a second run's rows, chosen to break this run if it reads them.
+
+ The worklists name a live person and a live mapping, so an unscoped read would delete them. The
+ exclusion tables name the person this run is deleting, so an unscoped read would spare it.
+ """
+
+ def seed(client: Client) -> None:
+ client.execute(
+ f"INSERT INTO {CLEANUP_DELETED_PERSONS_TABLE} (run_id, team_id, person_id, max_version) VALUES",
+ [(DECOY_RUN_ID, TEAM_ID, spared_person, 0)],
+ )
+ client.execute(
+ f"INSERT INTO {CLEANUP_ORPHANED_DISTINCT_IDS_TABLE}"
+ " (run_id, team_id, distinct_id, person_id, own_tombstone, max_version) VALUES",
+ [(DECOY_RUN_ID, TEAM_ID, spared_distinct_id, spared_person, 1, 0)],
+ )
+ client.execute(
+ f"INSERT INTO {CLEANUP_REVIVED_PERSONS_TABLE} (run_id, team_id, person_id) VALUES",
+ [(DECOY_RUN_ID, TEAM_ID, doomed_person)],
+ )
+ client.execute(
+ f"INSERT INTO {CLEANUP_REVIVED_DISTINCT_IDS_TABLE} (run_id, team_id, distinct_id) VALUES",
+ [(DECOY_RUN_ID, TEAM_ID, "gone")],
+ )
+
+ cluster.any_host(seed).result()
+ cluster.map_all_hosts(
+ lambda client: [client.execute(f"SYSTEM SYNC REPLICA {table} STRICT") for table in CLEANUP_SNAPSHOT_TABLES]
+ ).result()
+
+
+def queued_rows(conn) -> list[tuple]:
+ with conn.cursor() as cursor:
+ cursor.execute(f"SELECT team_id, person_uuid, deleted_at, cleaned_at FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 2")
+ return cursor.fetchall()
+
+
+def seed_cohort_rows(cluster: ClickhouseCluster, count: int) -> None:
+ rows = [(TEAM_ID, UUID(int=i), COHORT_ID, 1) for i in range(count)]
+ cluster.any_host(
+ lambda client: client.execute("INSERT INTO cohortpeople (team_id, person_id, cohort_id, sign) VALUES", rows)
+ ).result()
+
+
+def test_deletes_soft_deleted_persons_and_preserves_the_rest(cluster: ClickhouseCluster, persons_database):
+ # Deleted at a later version: every version has to go, which is why the delete keys on the
+ # person rather than on is_deleted.
+ deleted_later = create_person(team_id=TEAM_ID, version=0, is_deleted=False)
+ create_person(uuid=deleted_later, team_id=TEAM_ID, version=1, is_deleted=True)
+ # Deleted at its only version.
+ deleted_once = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ # Never deleted.
+ live = create_person(team_id=TEAM_ID, version=0)
+ # Deleted, then revived by a higher version: currently live, so it has to survive. Dropping the
+ # argMax gate for a plain is_deleted check would delete this person.
+ revived = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person(uuid=revived, team_id=TEAM_ID, version=1, is_deleted=False)
+
+ run_job(cluster, persons_database)
+
+ # The live version of deleted_later would survive a delete keyed on is_deleted rather than on
+ # the person, so this asserts on the raw count rather than the collapsed one.
+ assert cluster.any_host(rows_for(deleted_later)).result() == 0
+ assert cluster.any_host(rows_for(deleted_once)).result() == 0
+ assert cluster.any_host(rows_for(live)).result() == 1
+ assert cluster.any_host(rows_for(revived)).result() > 0
+ # Survivor counts go through FINAL: a background merge may collapse the revived person's two
+ # versions at any point, so its raw count is not stable.
+ assert cluster.any_host(current_persons).result() == 2
+
+
+def test_removes_distinct_ids_of_deleted_persons_and_keeps_live_ones(cluster: ClickhouseCluster, persons_database):
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ live = create_person(team_id=TEAM_ID, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="gone", person_id=deleted, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="kept", person_id=live, version=0)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == {"kept"}
+
+
+def test_removes_a_distinct_id_that_tombstoned_itself(cluster: ClickhouseCluster, persons_database):
+ # The mapping is tombstoned while its person stays live, which is the leak the person-driven
+ # arm alone would miss.
+ live = create_person(team_id=TEAM_ID, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="detached", person_id=live, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="detached", person_id=live, version=100, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="kept", person_id=live, version=0)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == {"kept"}
+
+
+def test_keeps_a_distinct_id_repointed_to_a_live_person(cluster: ClickhouseCluster, persons_database):
+ # Newest version points at a live person, so the mapping is in use and has to stay whole.
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ live = create_person(team_id=TEAM_ID, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="moved", person_id=deleted, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="moved", person_id=live, version=1)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == {"moved"}
+ assert cluster.any_host(current_owner("moved")).result() == UUID(live)
+
+
+def test_removes_every_version_of_a_distinct_id_repointed_to_a_deleted_person(
+ cluster: ClickhouseCluster, persons_database
+):
+ # Newest version points at a deleted person. Deleting only the rows whose person_id matches
+ # would strip that row and hand the mapping back to the live person underneath it.
+ live = create_person(team_id=TEAM_ID, version=0)
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="moved", person_id=live, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="moved", person_id=deleted, version=1)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == set()
+ assert cluster.any_host(current_owner("moved")).result() is None
+
+
+def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, persons_database):
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person(team_id=TEAM_ID, version=0)
+
+ run_job(cluster, persons_database)
+
+ rows = queued_rows(persons_database)
+ assert len(rows) == 1
+ team_id, person_uuid, deleted_at, cleaned_at = rows[0]
+ assert (team_id, str(person_uuid)) == (TEAM_ID, deleted)
+ assert deleted_at is not None
+ assert cleaned_at is None
+
+ # A second run must not raise on the primary key: it re-queues persons the drain has not
+ # reached yet.
+ run_job(cluster, persons_database)
+ assert len(queued_rows(persons_database)) == 1
+
+
+def test_queues_every_person_across_page_boundaries(cluster: ClickhouseCluster, persons_database, monkeypatch):
+ # The handoff pages its ClickHouse read by keyset and commits per page; an off-by-one at a
+ # page edge, or stopping after a full page that happened to be the last, silently drops
+ # persons from the queue and leaks their Postgres rows forever.
+ monkeypatch.setattr(clickhouse_cleanup, "PERSIST_PAGE_SIZE", 2)
+ expected = sorted(create_person(team_id=TEAM_ID, version=0, is_deleted=True) for _ in range(5))
+
+ run_job(cluster, persons_database)
+
+ assert sorted(str(row[1]) for row in queued_rows(persons_database)) == expected
+
+
+def test_requeues_a_person_the_drain_already_cleaned(cluster: ClickhouseCluster, persons_database):
+ # A person can be deleted, drained, then re-created and deleted again under the same uuid. The
+ # drain only reads rows where cleaned_at is null, so leaving the cleaned row untouched would
+ # drop the second deletion and leak that person's Postgres rows for good.
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ run_job(cluster, persons_database)
+
+ # Stand in for the drain having processed it.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET cleaned_at = now()")
+ persons_database.commit()
+ assert queued_rows(persons_database)[0][3] is not None
+
+ # The same person is deleted again at a higher version, so a later run snapshots it afresh.
+ create_person(uuid=deleted, team_id=TEAM_ID, version=10, is_deleted=True)
+ run_job(cluster, persons_database)
+
+ rows = queued_rows(persons_database)
+ assert len(rows) == 1, "the row is keyed on (team_id, person_uuid), so this stays a single row"
+ assert rows[0][3] is None, "cleaned_at must be cleared so the drain picks the person up again"
+
+
+def test_a_capped_run_deletes_a_slice_and_the_next_run_drains_the_rest(cluster: ClickhouseCluster, persons_database):
+ # max_persons bounds one run's blast radius; correctness across runs holds because whatever
+ # the cap excludes keeps its tombstones. Dropping the cap plumbing or making the capped
+ # populate non-deterministic breaks the convergence this asserts.
+ for _ in range(3):
+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ capped = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False, "max_persons": 2}}}}
+
+ run_job(cluster, persons_database, run_config=capped)
+ assert cluster.any_host(visible_persons).result() == 1
+ assert len(queued_rows(persons_database)) == 2
+
+ run_job(cluster, persons_database, run_config=capped)
+ assert cluster.any_host(visible_persons).result() == 0
+ assert len(queued_rows(persons_database)) == 3
+
+
+def test_a_team_range_limits_the_sweep_to_those_teams(cluster: ClickhouseCluster, persons_database):
+ inside = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ outside = create_person(team_id=TEAM_ID + 1, version=0, is_deleted=True)
+ ranged = {
+ "ops": {
+ "clear_removed_cohort_data": {"config": {"dry_run": False, "min_team_id": TEAM_ID, "max_team_id": TEAM_ID}}
+ }
+ }
+
+ run_job(cluster, persons_database, run_config=ranged)
+
+ assert cluster.any_host(rows_for(inside)).result() == 0
+ outside_rows = cluster.any_host(
+ lambda client: client.execute(
+ "SELECT count() FROM person WHERE team_id = %(t)s AND id = %(id)s",
+ {"t": TEAM_ID + 1, "id": outside},
+ )[0][0]
+ ).result()
+ assert outside_rows == 1
+ # Cleanup: the out-of-range person is outside the harness truncation scope for TEAM_ID.
+ run_job(cluster, persons_database)
+
+
+def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_database):
+ # The upsert's conflict guard skips rows that already hold the incoming values. Without it a
+ # Dagster retry of this op writes a new tuple version for every queued person, and a retry
+ # over millions of rows leaves that many dead tuples on the persons writer. A full second job
+ # run cannot exercise this: the first run hard-deletes the ClickHouse rows, so the op never
+ # upserts the same person twice. The op is invoked directly instead, as a retry would.
+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ run = clickhouse_cleanup.CleanupRun.for_run("persist_retry_run", clickhouse_cleanup.CleanupConfig(dry_run=False))
+ cluster.any_host(run.persons.populate).result()
+ cluster.map_all_hosts(run.persons.sync_replica).result()
+ run = replace(run, distinct_ids_deleted_at=datetime(2026, 1, 1, tzinfo=UTC), persons_count=1)
+
+ def queue_row() -> tuple:
+ # xmin changes on every UPDATE, so a stable xmin proves no new tuple version was written.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"SELECT xmin::text, deleted_at, cleaned_at FROM {PG_CLEANUP_QUEUE_TABLE}")
+ [row] = cursor.fetchall()
+ return row
+
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)
+ first = queue_row()
+
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)
+ assert queue_row() == first
+
+ # A drained row must still be re-armed even when deleted_at matches, or the second deletion
+ # of a re-created person is dropped.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET cleaned_at = now()")
+ persons_database.commit()
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)
+ rearmed = queue_row()
+ assert rearmed[2] is None
+ assert rearmed[0] != first[0]
+
+
+def test_excludes_a_person_revived_while_the_run_is_in_flight(cluster: ClickhouseCluster, persons_database):
+ revived = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="spared", person_id=revived, version=0)
+ doomed = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="gone", person_id=doomed, version=0)
+
+ original = OrphanedDistinctIdsTable.populate
+
+ def revive_then_populate(self, client, persons_dictionary, settings=None):
+ # Fires after the snapshot is taken and the dictionary is loaded, so the checkpoint is
+ # the only thing standing between the revived person and the delete.
+ create_person(uuid=revived, team_id=TEAM_ID, version=10, is_deleted=False)
+ return original(self, client, persons_dictionary, settings=settings)
+
+ with patch.object(OrphanedDistinctIdsTable, "populate", revive_then_populate):
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == {"spared"}
+ assert cluster.any_host(rows_for(doomed)).result() == 0
+ assert cluster.any_host(rows_for(revived)).result() > 0
+ # The queued set has to match the set deleted in ClickHouse. If they diverge, the Postgres
+ # drain clears a person that is still live here.
+ assert [str(row[1]) for row in queued_rows(persons_database)] == [doomed]
+
+
+def test_no_op_when_nothing_is_soft_deleted(cluster: ClickhouseCluster, persons_database):
+ # The snapshot is empty, so the dictionary source returns nothing and dictHas never matches.
+ live = create_person(team_id=TEAM_ID, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="kept", person_id=live, version=0)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(visible_persons).result() == 1
+ assert cluster.any_host(surviving_distinct_ids).result() == {"kept"}
+ assert queued_rows(persons_database) == []
+
+
+def test_is_idempotent(cluster: ClickhouseCluster, persons_database):
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="gone", person_id=deleted, version=0)
+ create_person(team_id=TEAM_ID, version=0)
+
+ run_job(cluster, persons_database)
+ # The first run tombstones the deleted rows, so the second snapshot no longer sees them.
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(visible_persons).result() == 1
+ assert cluster.any_host(surviving_distinct_ids).result() == set()
+
+
+def test_dry_run_deletes_nothing(cluster: ClickhouseCluster, persons_database):
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="gone", person_id=deleted, version=0)
+ seed_cohort_rows(cluster, count=5)
+ AsyncDeletion.objects.create(deletion_type=DeletionType.Cohort_full, team_id=TEAM_ID, key=f"{COHORT_ID}_0")
+
+ run_job(cluster, persons_database, run_config=None)
+
+ assert cluster.any_host(visible_persons).result() == 1
+ assert cluster.any_host(surviving_distinct_ids).result() == {"gone"}
+ assert cluster.any_host(cohort_rows).result() == 5
+ assert queued_rows(persons_database) == []
+ assert AsyncDeletion.objects.get(team_id=TEAM_ID).delete_verified_at is None
+
+
+def test_drops_the_dictionaries_and_clears_the_run_rows(cluster: ClickhouseCluster, persons_database):
+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+
+ result = run_job(cluster, persons_database)
+
+ # A leaked dictionary holds its key set in memory on every host. The rows are cheaper, but the
+ # tables are shared, so a run that never clears its own rows makes every later run read them.
+ assert cluster.any_host(dictionaries_for_run(result.run_id)).result() == 0
+ assert cluster.any_host(snapshot_rows_for_run(result.run_id)).result() == 0
+
+
+def test_clears_cohort_rows_and_marks_the_deletion_verified_on_the_next_run(
+ 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")
+
+ run_job(cluster, persons_database)
+
+ # The mark pass runs before the delete pass, so it sees rows that are still present and
+ # verification lands a run later. A reordering that drops the mark pass would leave
+ # AsyncDeletion rows unverified forever, and they would be re-swept every week.
+ assert cluster.any_host(cohort_rows).result() == 0
+ assert AsyncDeletion.objects.get(team_id=TEAM_ID).delete_verified_at is None
+
+ run_job(cluster, persons_database)
+
+ assert AsyncDeletion.objects.get(team_id=TEAM_ID).delete_verified_at is not None
+
+
+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",
+ side_effect=Exception("boom"),
+ ):
+ result = run_job(cluster, persons_database)
+
+ # Collapsing the two guards into one try would skip the pass that actually removes rows.
+ assert result.success
+ assert cluster.any_host(cohort_rows).result() == 0
+
+
+def test_cohort_sweep_runs_even_when_the_person_delete_fails(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")
+
+ with patch(
+ "posthog.dags.clickhouse_cleanup.LightweightDeleteMutationRunner",
+ side_effect=Exception("boom"),
+ ):
+ result = run_job(cluster, persons_database, raise_on_error=False)
+
+ # Moving the cohort sweep back downstream of the person path would strand cohort rows every
+ # week that path ran long or failed, which is why it goes first.
+ assert not result.success
+ assert cluster.any_host(cohort_rows).result() == 0
+
+
+def test_a_run_ignores_another_runs_snapshot_rows(cluster: ClickhouseCluster, persons_database):
+ # Runs share the snapshot tables, so every read of them has to be scoped by run id. Drop any
+ # one of those WHERE clauses and this fails: the decoy's worklist rows delete a live person and
+ # a live mapping, and its exclusion rows spare the person this run is deleting.
+ live = create_person(team_id=TEAM_ID, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="kept", person_id=live, version=0)
+ doomed = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="gone", person_id=doomed, version=0)
+
+ seed_decoy_run(cluster, spared_person=live, spared_distinct_id="kept", doomed_person=doomed)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(rows_for(live)).result() == 1
+ assert cluster.any_host(surviving_distinct_ids).result() == {"kept"}
+ assert cluster.any_host(rows_for(doomed)).result() == 0
+ assert [str(row[1]) for row in queued_rows(persons_database)] == [doomed]
+ # Clearing rows at the end of a run has to be scoped too, or one run wipes another's worklist.
+ assert cluster.any_host(snapshot_rows_for_run(DECOY_RUN_ID)).result() > 0
+
+
+def test_a_failed_run_drops_its_dictionaries_and_keeps_its_rows(cluster: ClickhouseCluster, persons_database):
+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+
+ # Fails once the dictionaries are built, so there is something to strand.
+ with patch(
+ "posthog.dags.clickhouse_cleanup.LightweightDeleteMutationRunner",
+ side_effect=Exception("boom"),
+ ):
+ result = run_job(cluster, persons_database, raise_on_error=False)
+
+ assert not result.success
+ # Dagster skips drop_snapshot_assets after a failure, so without the hook the dictionaries
+ # would survive on every host and accumulate across failed runs.
+ assert cluster.any_host(dictionaries_for_run(result.run_id)).result() == 0
+ # The rows survive on purpose: they cost far less than a dictionary, the tables' TTL reaps
+ # them, and they are what makes a failed sweep inspectable in the meantime.
+ assert cluster.any_host(snapshot_rows_for_run(result.run_id)).result() > 0
+
+
+def test_keeps_a_distinct_id_recaptured_while_the_run_is_in_flight(cluster: ClickhouseCluster, persons_database):
+ live = create_person(team_id=TEAM_ID, version=0)
+ for distinct_id in ("recaptured", "gone"):
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id=distinct_id, person_id=live, version=0)
+ create_person_distinct_id(
+ team_id=TEAM_ID, distinct_id=distinct_id, person_id=live, version=100, is_deleted=True
+ )
+
+ original = OrphanedDistinctIdsTable.populate
+
+ def recapture_then_populate(self, client, persons_dictionary, settings=None):
+ result = original(self, client, persons_dictionary, settings=settings)
+ # A client captures the id again after the snapshot froze the reason it qualified. Trusting
+ # that snapshot would delete every version of the mapping, including this live one.
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="recaptured", person_id=live, version=200)
+ return result
+
+ with patch.object(OrphanedDistinctIdsTable, "populate", recapture_then_populate):
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(surviving_distinct_ids).result() == {"recaptured"}
+ assert cluster.any_host(current_owner("recaptured")).result() == UUID(live)
+
+
+def versions_for(distinct_id: str):
+ def query(client: Client) -> list[int]:
+ rows = client.execute(
+ "SELECT version FROM person_distinct_id2 WHERE team_id = %(team_id)s AND distinct_id = %(d)s ORDER BY version",
+ {"team_id": TEAM_ID, "d": distinct_id},
+ )
+ return [row[0] for row in rows]
+
+ return query
+
+
+def current_deleted(distinct_id: str):
+ def query(client: Client) -> int | None:
+ rows = client.execute(
+ """
+ SELECT argMax(is_deleted, version) FROM person_distinct_id2
+ WHERE team_id = %(team_id)s AND distinct_id = %(d)s GROUP BY distinct_id
+ """,
+ {"team_id": TEAM_ID, "d": distinct_id},
+ )
+ return rows[0][0] if rows else None
+
+ return query
+
+
+def test_an_interrupted_sweep_leaves_the_tombstone_as_the_surviving_version(
+ cluster: ClickhouseCluster, persons_database
+):
+ # The reason the delete is ordered at all. The first pass runs for real; the second is cut off
+ # the way a killed or failed mutation would cut it off. The key must still resolve as deleted.
+ # Reverse the two passes and this fails: the tombstone goes first and the older live row is
+ # handed back to a person the run is about to delete.
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="doomed", person_id=deleted, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="doomed", person_id=deleted, version=100, is_deleted=True)
+
+ real_runner = clickhouse_cleanup.LightweightDeleteMutationRunner
+ calls = itertools.count()
+
+ def fail_on_the_second_pass(*args, **kwargs):
+ if next(calls) >= 1:
+ raise RuntimeError("interrupted between passes")
+ return real_runner(*args, **kwargs)
+
+ with patch.object(clickhouse_cleanup, "LightweightDeleteMutationRunner", fail_on_the_second_pass):
+ result = run_job(cluster, persons_database, raise_on_error=False)
+
+ assert not result.success
+ surviving = cluster.any_host(versions_for("doomed")).result()
+ assert surviving == [100], f"expected only the tombstone to survive, got {surviving}"
+ assert cluster.any_host(current_deleted("doomed")).result() == 1
+
+
+def test_removes_every_version_below_the_max_in_one_pass(cluster: ClickhouseCluster, persons_database):
+ # Depth must not drive the number of passes: three versions collapse in the same two passes
+ # as two do.
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ for version in (0, 5):
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="deep", person_id=deleted, version=version)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="deep", person_id=deleted, version=100, is_deleted=True)
+
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(versions_for("deep")).result() == []
+
+
+def test_rows_written_after_the_snapshot_survive(cluster: ClickhouseCluster, persons_database):
+ # Both passes are bounded by the snapshot's max_version, so a run never removes a row it did
+ # not observe.
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="racing", person_id=deleted, version=0)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="racing", person_id=deleted, version=100, is_deleted=True)
+
+ original = OrphanedDistinctIdsTable.populate
+
+ def write_after_snapshot(self, client, persons_dictionary, settings=None):
+ result = original(self, client, persons_dictionary, settings=settings)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="racing", person_id=deleted, version=500)
+ return result
+
+ with patch.object(OrphanedDistinctIdsTable, "populate", write_after_snapshot):
+ run_job(cluster, persons_database)
+
+ assert cluster.any_host(versions_for("racing")).result() == [500]
+
+
+def test_team_ranges_cover_every_candidate_team_exactly_once():
+ teams = [3, 1, 9, 4, 7, 2]
+ ranges = clickhouse_cleanup._team_ranges(teams, batches=3)
+
+ assert clickhouse_cleanup._team_ranges([], batches=4) == []
+ # Contiguous and non-overlapping, so no key falls between two batches.
+ assert [r.low for r in ranges] == sorted(r.low for r in ranges)
+ for earlier, later in zip(ranges, ranges[1:]):
+ assert earlier.high < later.low
+ for team in teams:
+ assert sum(1 for r in ranges if r.low <= team <= r.high) == 1
+
+
+def test_more_batches_than_teams_does_not_produce_empty_ranges():
+ ranges = clickhouse_cleanup._team_ranges([5, 6], batches=10)
+ assert ranges == [clickhouse_cleanup.TeamRange(low=5, high=5), clickhouse_cleanup.TeamRange(low=6, high=6)]
+
+
+def test_a_retried_snapshot_populate_cannot_skew_the_dictionary(cluster: ClickhouseCluster):
+ # An op retry re-runs populate, leaving duplicate key rows until a merge collapses them. The
+ # dictionary must read the newest max_version bound, not whichever duplicate it happens upon.
+ person = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ table = clickhouse_cleanup.DeletedPersonsTable(run_id="retry_run")
+ cluster.any_host(table.populate).result()
+ # The person gains a higher deleted version between the attempt and its retry.
+ create_person(uuid=person, team_id=TEAM_ID, version=3, is_deleted=True)
+ cluster.any_host(table.populate).result()
+ cluster.map_all_hosts(table.sync_replica).result()
+
+ dictionary = clickhouse_cleanup.SnapshotDictionary(
+ source=table, excluded=clickhouse_cleanup.RevivedPersonsTable(run_id="retry_run")
+ )
+ try:
+ cluster.map_all_hosts(partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()
+ cluster.map_all_hosts(dictionary.load, concurrency=1).result()
+ rows = cluster.any_host(
+ lambda client: client.execute(f"SELECT person_id, max_version FROM {dictionary.qualified_name}")
+ ).result()
+ assert rows == [(UUID(person), 3)]
+ finally:
+ cluster.map_all_hosts(dictionary.drop).result()
+ cluster.any_host(table.drop_run_partition).result()
+
+
+def test_a_reaped_snapshot_fails_the_delete_instead_of_under_deleting(cluster: ClickhouseCluster):
+ # The 14-day TTL drops a stalled run's partition; the delete must then fail loudly rather
+ # than sweep from a silently shrunken worklist.
+ run = clickhouse_cleanup.CleanupRun.for_run("reaped-run", clickhouse_cleanup.CleanupConfig(dry_run=False))
+ run = replace(run, persons_count=5)
+
+ with pytest.raises(dagster.Failure, match="snapshot TTL"):
+ clickhouse_cleanup.delete_persons(dagster.build_op_context(resources={"cluster": cluster}), run=run)
+
+
+T0 = datetime(2026, 1, 1, 12, 0, 0)
+
+
+def failing_status(fail_at: datetime, parts: int = 10, now: datetime | None = None) -> MutationStatus:
+ return MutationStatus(
+ done=False,
+ visible=True,
+ parts_to_do=parts,
+ latest_fail_time=fail_at,
+ latest_fail_reason="boom",
+ server_now=now or fail_at,
+ )
+
+
+def quiet_status(parts: int = 10, visible: bool = True) -> MutationStatus:
+ return MutationStatus(
+ done=False,
+ visible=visible,
+ parts_to_do=parts,
+ latest_fail_time=None,
+ latest_fail_reason="",
+ server_now=T0,
+ )
+
+
+def test_mutation_progress_tolerates_failures_while_parts_still_complete():
+ # ClickHouse retries failed part mutations itself; as long as parts keep completing the run
+ # must keep waiting. Reverting to fail-on-any-reason kills a batch that would have finished.
+ progress = MutationProgress(stall_timeout=100)
+ progress.observe([quiet_status(parts=20)], now=0)
+ for tick in range(1, 15):
+ progress.observe([failing_status(T0 + timedelta(seconds=tick * 60), parts=20 - tick)], now=tick * 60)
+
+
+def test_mutation_progress_declares_a_stall_when_failures_recur_without_progress():
+ progress = MutationProgress(stall_timeout=100)
+ progress.observe([quiet_status(parts=3), quiet_status(parts=10)], now=0)
+ progress.observe([quiet_status(parts=3), failing_status(T0 + timedelta(seconds=15))], now=15)
+ with pytest.raises(MutationStalled):
+ progress.observe([quiet_status(parts=3), failing_status(T0 + timedelta(seconds=120))], now=120)
+
+
+def test_mutation_progress_ignores_a_failure_that_predates_polling():
+ # MutationRunner can re-attach to an existing mutation whose old attempts failed; that history
+ # must not condemn a batch that has not failed since.
+ stale = T0 - timedelta(hours=6)
+ progress = MutationProgress(stall_timeout=100)
+ progress.observe([failing_status(stale, now=T0)], now=0)
+ progress.observe([failing_status(stale, now=T0 + timedelta(seconds=200))], now=200)
+ with pytest.raises(MutationStalled):
+ progress.observe([failing_status(T0 + timedelta(seconds=300))], now=300)
+
+
+def test_mutation_progress_counts_a_failure_just_before_the_first_poll():
+ # A freshly enqueued mutation can fail before the first poll lands; unlike a re-attached
+ # mutation's stale history, that failure is evidence.
+ progress = MutationProgress(stall_timeout=100)
+ progress.observe([failing_status(T0 - timedelta(seconds=5), now=T0)], now=0)
+ with pytest.raises(MutationStalled):
+ progress.observe([failing_status(T0 - timedelta(seconds=5), now=T0 + timedelta(seconds=150))], now=150)
+
+
+def test_mutation_progress_fails_a_healthy_mutation_past_the_wait_deadline():
+ # A mutation blocked behind another mutation is healthy and makes no progress; without the
+ # deadline that run waits forever and raises no alert.
+ progress = MutationProgress(stall_timeout=600, wait_deadline=1000)
+ progress.observe([quiet_status(parts=5)], now=0.0)
+ progress.observe([quiet_status(parts=5)], now=999.0)
+ with pytest.raises(MutationStalled, match="not finished after 1000"):
+ progress.observe([quiet_status(parts=5)], now=1001.0)
+
+
+def test_mutation_progress_waits_on_a_slow_mutation_that_is_not_failing():
+ # No failures means a big part or a busy cluster; declaring that stuck would kill every
+ # long-running healthy batch.
+ progress = MutationProgress(stall_timeout=100)
+ for tick in range(100):
+ progress.observe([quiet_status(parts=10)], now=tick * 60)
+
+
+def test_mutation_progress_tolerates_brief_invisibility_and_fails_when_it_persists():
+ # The mutation entry replicates through Keeper, so a lagged replica briefly not knowing it is
+ # normal; a replica that never learns of it is not.
+ progress = MutationProgress(stall_timeout=100, visibility_timeout=300)
+ progress.observe([quiet_status(visible=False)], now=0)
+ progress.observe([quiet_status(visible=False)], now=299)
+ with pytest.raises(MutationStalled):
+ progress.observe([quiet_status(visible=False)], now=301)
+
+
+def test_a_mutation_that_fails_every_attempt_fails_the_run_and_gets_killed(
+ cluster: ClickhouseCluster, persons_database, monkeypatch
+):
+ deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ create_person_distinct_id(team_id=TEAM_ID, distinct_id="doomed", person_id=deleted, version=0)
+
+ monkeypatch.setattr(clickhouse_cleanup, "MUTATION_POLL_SECONDS", 0.1)
+ real_runner = clickhouse_cleanup.LightweightDeleteMutationRunner
+
+ def poisoned_runner(*args, **kwargs):
+ # Fails at part-mutation time on every attempt, not at submission: the predicate reads a
+ # column, so ClickHouse cannot constant-fold the throw during validation.
+ kwargs["predicate"] = f"throwIf(version >= 0, 'poisoned sweep') OR ({kwargs['predicate']})"
+ return real_runner(*args, **kwargs)
+
+ stalling = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False, "mutation_stall_timeout": 1}}}}
+ with patch.object(clickhouse_cleanup, "LightweightDeleteMutationRunner", poisoned_runner):
+ result = run_job(cluster, persons_database, run_config=stalling, raise_on_error=False)
+
+ assert not result.success
+ # The poisoned mutation never applied, so the data is intact.
+ assert cluster.any_host(surviving_distinct_ids).result() == {"doomed"}
+
+ # The failure hook must kill the stuck mutation, or it retries in the background forever and
+ # blocks every later mutation on the table.
+ def unfinished_mutations(client: Client) -> int:
+ [[count]] = client.execute(
+ "SELECT count() FROM system.mutations WHERE NOT is_done AND NOT is_killed AND table = %(table)s",
+ {"table": "person_distinct_id2"},
+ )
+ return count
+
+ assert cluster.any_host(unfinished_mutations).result() == 0
diff --git a/posthog/dags/tests/test_common_dictionaries.py b/posthog/dags/tests/test_common_dictionaries.py
new file mode 100644
index 000000000000..b9964105b940
--- /dev/null
+++ b/posthog/dags/tests/test_common_dictionaries.py
@@ -0,0 +1,185 @@
+import itertools
+from collections.abc import Iterable
+from datetime import datetime
+from typing import Any, cast
+
+import pytest
+
+from clickhouse_driver.client import Client
+
+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser
+from posthog.dags import clickhouse_cleanup
+from posthog.dags.common import dictionaries
+from posthog.dags.common.dictionaries import Dictionary
+from posthog.dags.common.staged_dictionary import StagedDictionary
+from posthog.dags.deletes import (
+ AdhocEventDeletesDictionary,
+ AdhocEventDeletesTable,
+ PendingDeletesDictionary,
+ PendingDeletesTable,
+)
+from posthog.dataclasses import frozen
+
+
+@frozen
+class _StubDictionary(Dictionary):
+ @property
+ def name(self) -> str:
+ return "stub_dictionary"
+
+ @property
+ def schema(self) -> str:
+ return "team_id Int64, key String"
+
+ @property
+ def primary_key(self) -> str:
+ return "team_id, key"
+
+ @property
+ def query(self) -> str:
+ return "SELECT team_id, key FROM stub_source"
+
+ def staged(self) -> StagedDictionary:
+ return StagedDictionary(key="stub.parquet", columns="team_id, key", structure=self.schema)
+
+
+class _ScriptedClient:
+ """Answers dictionary-status polls from a script and records every statement."""
+
+ def __init__(self, statuses: Iterable[tuple[str, str] | None] = (), checksum: int = 0) -> None:
+ self.statuses = iter(statuses)
+ self.checksum = checksum
+ self.executed: list[tuple[str, dict[str, Any] | None]] = []
+
+ def execute(self, query: str, params: dict[str, Any] | None = None) -> list[list[Any]]:
+ self.executed.append((query, params))
+ if "system.dictionaries" in query:
+ status = next(self.statuses)
+ return [] if status is None else [list(status)]
+ if "groupBitXor" in query:
+ return [[self.checksum]]
+ return []
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.now += seconds
+
+
+def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:
+ clock = _Clock()
+ monkeypatch.setattr(dictionaries.time, "monotonic", clock.monotonic)
+ monkeypatch.setattr(dictionaries.time, "sleep", clock.sleep)
+ return clock
+
+
+def test_load_returns_the_checksum_once_loaded(clock: _Clock) -> None:
+ client = _ScriptedClient(statuses=[("LOADING", ""), ("LOADED", "")], checksum=42)
+ assert _StubDictionary(load_timeout=600).load(cast(Client, client)) == 42
+
+
+def test_load_fails_instead_of_waiting_forever_on_a_wedged_dictionary(clock: _Clock) -> None:
+ client = _ScriptedClient(statuses=itertools.repeat(("LOADING", "")))
+ with pytest.raises(Exception, match="still not loaded after 600"):
+ _StubDictionary(load_timeout=600).load(cast(Client, client))
+
+
+ "status,match",
+ [
+ (("FAILED", "grant missing"), "failed to load: grant missing"),
+ (("MYSTERY", ""), "unexpected status: MYSTERY"),
+ (None, "does not exist"),
+ ],
+)
+def test_load_surfaces_terminal_statuses(clock: _Clock, status: tuple[str, str] | None, match: str) -> None:
+ client = _ScriptedClient(statuses=[status])
+ with pytest.raises(Exception, match=match):
+ _StubDictionary().load(cast(Client, client))
+
+
+def test_checksum_covers_every_column_without_sorting() -> None:
+ # groupBitXor is order independent, so a sort would only cost time and memory on a
+ # dictionary holding tens of millions of rows per host.
+ client = _ScriptedClient(checksum=7)
+ assert _StubDictionary().checksum(cast(Client, client)) == 7
+ [(query, _)] = client.executed
+ assert "groupBitXor(cityHash64(*))" in query
+ assert "ORDER BY" not in query
+
+
+def _pending_deletes_dictionary() -> PendingDeletesDictionary:
+ return PendingDeletesDictionary(source=PendingDeletesTable(timestamp=datetime(2026, 1, 1)))
+
+
+def _adhoc_event_deletes_dictionary() -> AdhocEventDeletesDictionary:
+ return AdhocEventDeletesDictionary(source=AdhocEventDeletesTable())
+
+
+def _snapshot_dictionary() -> clickhouse_cleanup.SnapshotDictionary:
+ return clickhouse_cleanup.SnapshotDictionary(
+ source=clickhouse_cleanup.DeletedPersonsTable(run_id="run_1"),
+ excluded=clickhouse_cleanup.RevivedPersonsTable(run_id="run_1"),
+ )
+
+
+ "make_dictionary,expected_user",
+ [
+ (_pending_deletes_dictionary, "app_default"),
+ (_adhoc_event_deletes_dictionary, "app_default"),
+ (_snapshot_dictionary, "reader"),
+ ],
+)
+def test_create_reads_the_source_as_each_callers_credentials(
+ monkeypatch: pytest.MonkeyPatch, make_dictionary: Any, expected_user: str
+) -> None:
+ # The GDPR job's dictionaries must keep reading as the default user until dict_reader's
+ # SELECT grants on its per-run tables are proven in every environment; the sweep already
+ # reads as dict_reader. A shared-lifecycle change that flips either breaks a weekly prod job.
+ creds = {
+ ClickHouseUser.DEFAULT: ClickHouseCredentials(user="app_default", password="p1"),
+ ClickHouseUser.DICT_READER: ClickHouseCredentials(user="reader", password="p2"),
+ }
+ monkeypatch.setattr(dictionaries, "get_clickhouse_creds", creds.__getitem__)
+ monkeypatch.setattr(clickhouse_cleanup, "get_clickhouse_creds", creds.__getitem__)
+
+ client = _ScriptedClient()
+ make_dictionary().create(cast(Client, client), shards=1, max_execution_time=0, max_memory_usage=0)
+
+ [(query, params)] = client.executed
+ assert "CREATE DICTIONARY" in query
+ assert params is not None and params["user"] == expected_user
+
+
+def test_create_can_read_a_staged_object_instead_of_the_source() -> None:
+ # create_on_every_cluster hands the far cluster the staged query; the source query must not
+ # leak through or that cluster reads a table it cannot see.
+ client = _ScriptedClient()
+ dictionary = _pending_deletes_dictionary()
+ dictionary.create(cast(Client, client), shards=1, max_execution_time=0, max_memory_usage=0, query="SELECT 1")
+ [(_, params)] = client.executed
+ assert params is not None and params["query"] == "SELECT 1"
+
+
[email protected]("make_dictionary", [_pending_deletes_dictionary, _adhoc_event_deletes_dictionary])
+def test_deletes_job_dictionaries_stage_under_their_own_name(make_dictionary: Any) -> None:
+ dictionary = make_dictionary()
+ staged = dictionary.staged()
+ assert staged.key == f"{dictionary.name}.parquet"
+ assert staged.structure == dictionary.schema
+
+
+def test_sweep_dictionaries_refuse_staging() -> None:
+ # A staged copy is static; the sweep's checkpoints exclude revived keys by reloading, so a
+ # staged copy on another cluster would keep deleting persons that came back to life. Failing
+ # at create time is the safe outcome if the person tables ever gain a second placement.
+ with pytest.raises(NotImplementedError, match="cannot be staged"):
+ _snapshot_dictionary().staged()
diff --git a/posthog/management/commands/start_delete_mutation.py b/posthog/management/commands/start_delete_mutation.py
index 5a9bdac5b7f5..1d69d9a80c25 100644
--- a/posthog/management/commands/start_delete_mutation.py
+++ b/posthog/management/commands/start_delete_mutation.py
@@ -4,7 +4,7 @@ from django.core.management.base import BaseCommand
import structlog
-from posthog.tasks.tasks import clickhouse_clear_removed_data
+from posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions
logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
@@ -22,5 +22,5 @@ class Command(BaseCommand):
def run():
logger.info("Starting deletion of data for teams")
- clickhouse_clear_removed_data()
- logger.info("Finished deletion of data for teams")
+ failed = sweep_cohort_deletions()
+ logger.info("Finished deletion of data for teams", failed_passes=failed)
diff --git a/posthog/models/async_deletion/delete_cohorts.py b/posthog/models/async_deletion/delete_cohorts.py
index f8aa9fa28290..ad77f6ef431d 100644
--- a/posthog/models/async_deletion/delete_cohorts.py
+++ b/posthog/models/async_deletion/delete_cohorts.py
@@ -1,9 +1,28 @@
from typing import Any
+from more_itertools import chunked
+from prometheus_client import Counter
+
from posthog.clickhouse.client import sync_execute
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.async_deletion.delete import AsyncDeletionProcess, logger
+COHORT_DELETION_MARK_FAILURE_COUNTER = Counter(
+ "posthog_cohort_deletion_mark_failure_total",
+ "Times cohort deletion mark failed",
+)
+
+COHORT_DELETION_RUN_FAILURE_COUNTER = Counter(
+ "posthog_cohort_deletion_run_failure_total",
+ "Times cohort deletion run failed",
+)
+
+
+# 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.
+COHORT_DELETION_CHUNK_SIZE = 500
+
class AsyncCohortDeletion(AsyncDeletionProcess):
DELETION_TYPES = [DeletionType.Cohort_full, DeletionType.Cohort_stale]
@@ -21,17 +40,18 @@ class AsyncCohortDeletion(AsyncDeletionProcess):
},
)
- conditions, args = self._conditions(deletions)
+ 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={},
- )
+ # nosemgrep: clickhouse-fstring-param-audit - conditions from internal _conditions method
+ sync_execute(
+ f"""
+ DELETE FROM cohortpeople
+ WHERE {" OR ".join(conditions)}
+ """,
+ args,
+ settings={},
+ )
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:
@@ -43,18 +63,21 @@ class AsyncCohortDeletion(AsyncDeletionProcess):
return []
def _verify_by_column(self, distinct_columns: str, async_deletions: list[AsyncDeletion]) -> set[tuple[Any, ...]]:
- conditions, args = self._conditions(async_deletions)
- # 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={},
- )
- return {tuple(row) for row in clickhouse_result}
+ 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
def _column_name(self, async_deletion: AsyncDeletion):
assert async_deletion.deletion_type in (
@@ -86,3 +109,29 @@ class AsyncCohortDeletion(AsyncDeletionProcess):
key_param: key,
},
)
+
+
+def sweep_cohort_deletions() -> list[str]:
+ """Run both cohort deletion passes and return the names of any that failed.
+
+ 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.
+ """
+ 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
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 0ccdf4f5ca7e..2175379d4556 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -53,16 +53,6 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_CHUNK_FAILURE_COUNTER = Counter(
)
-COHORT_DELETION_MARK_FAILURE_COUNTER = Counter(
- "posthog_cohort_deletion_mark_failure_total",
- "Times cohort deletion mark failed",
-)
-
-COHORT_DELETION_RUN_FAILURE_COUNTER = Counter(
- "posthog_cohort_deletion_run_failure_total",
- "Times cohort deletion run failed",
-)
-
STALE_QUEUED_TASK_RUN_SWEPT_COUNTER = Counter(
"posthog_task_run_stale_queued_swept_total",
"TaskRuns marked FAILED by the stale-queued cleanup sweep",
@@ -760,21 +750,9 @@ def clickhouse_mutation_count() -> None:
@shared_task(ignore_result=True)
def clickhouse_clear_removed_data() -> None:
- from posthog.models.async_deletion.delete_cohorts import AsyncCohortDeletion
-
- cohort_runner = AsyncCohortDeletion()
+ from posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions
- try:
- cohort_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()
-
- try:
- cohort_runner.run()
- except Exception as e:
- logger.error("Failed to run cohort deletions", error=e, exc_info=True)
- COHORT_DELETION_RUN_FAILURE_COUNTER.inc()
+ sweep_cohort_deletions()
@shared_task(ignore_result=True)
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 87447aa52536..a2c997e17ceb 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -52,6 +52,7 @@ from posthog.clickhouse.adhoc_events_deletion import (
ADHOC_EVENTS_DELETION_TABLE_SQL,
DROP_ADHOC_EVENTS_DELETION_TABLE_SQL,
)
+from posthog.clickhouse.cleanup_snapshots import CLEANUP_SNAPSHOT_TABLE_SQL, DROP_CLEANUP_SNAPSHOT_TABLE_SQL
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import get_client_from_pool
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
@@ -2030,6 +2031,7 @@ def reset_clickhouse_database() -> None:
DROP_EXCHANGE_RATE_DICTIONARY_SQL(),
DROP_WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_SQL(),
DROP_ADHOC_EVENTS_DELETION_TABLE_SQL(),
+ *[drop_sql() for drop_sql in DROP_CLEANUP_SNAPSHOT_TABLE_SQL],
]
)
run_clickhouse_statement_in_parallel(
@@ -2152,6 +2154,7 @@ def reset_clickhouse_database() -> None:
SESSIONS_TABLE_MV_SQL(),
SESSIONS_VIEW_SQL(),
ADHOC_EVENTS_DELETION_TABLE_SQL(),
+ *[table_sql() for table_sql in CLEANUP_SNAPSHOT_TABLE_SQL],
CUSTOM_METRICS_VIEW(include_counters=True),
WEB_PRE_AGGREGATED_TEAM_SELECTION_DATA_SQL(),
COHORT_MEMBERSHIP_MV_SQL(),