:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(deletes): skip sharded_events_json, configurable per run (#102195)
Paweł Szczur4d673102f1ee
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex fcfda2c960a2..c97628d81c7a 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -91,7 +91,7 @@ Skipping one of those tables is worse than under-deleting: the overrides that re## Covered tables- `sharded_events` — all sweeps.-- `sharded_events_json` — all sweeps. Optional: only present after the native-JSON migration.+- `sharded_events_json` — all sweeps, but `deletes_job` skips it by default today. Optional: only present after the native-JSON migration. See the known gap below.- `sharded_flag_evaluations` — person, team, queued-uuid and event removal. Not property removal (below). Optional.- `sharded_posthog_document_embeddings_<model>` — event and team deletion, through `delete_event_documents`. An embedded document is keyed by the id of the thing it describes (`document_id`), and an Event deletion's key is that same id, so the pending dictionary is joined on `(team_id, Event, document_id)`. Every per-model table listed by the error tracking facade's `document_embedding_tables` is swept and counted.@@ -109,6 +109,29 @@ That decision predates this document; the older `posthog/models/async_deletion/d## Known gaps+### `deletes_job` skips `sharded_events_json` by default++`SweepTargetsConfig.skip_targets` defaults to `["sharded_events_json"]`, so the weekly sweep leaves+that table alone and does not address the events cluster at all.++The table's storage is on the events cluster, which `deletes_job` reaches through a sibling handle.+Resolving that handle has not been reliable: a run that fails to resolve it drops the target and+still marks the requests verified, which reports an erasure that did not happen. Skipping the target+outright makes the sweep say so, in `resolve_sweep_targets`, rather than leaving the outcome to+whether one probe answered.++The cost is that rows `sharded_events_json` holds for a deleted person, team or queued uuid stay+readable, and the requests covering them are marked verified either way, so a later run does not+return to them. The table is dual-written from the same events, so those rows duplicate ones the+sweep does remove from `sharded_events`.++To sweep it again:++- For one run, set `skip_targets: []` under the `resolve_sweep_targets` op in run config.+- Permanently, remove the entry from `_DEFAULT_SKIP_TARGETS` in `posthog/dags/deletes.py`.++Neither restores what earlier runs left behind. That needs a backfill sweep over the affected uuids.+### Property removal does not reach `flag_evaluations``person_properties` and `group0..group4_properties` no longer exist on the table: no Insight or Hog function used either as a breakdown or a filter, so the ClickHouse team dropped them directly on both prod clusters, and `posthog/models/flag_evaluations/sql.py` no longer declares them, so any environment built from the migrations matches. Event `properties` and `person_id` are still sent.diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex 9b85c689ab3b..0fc21da8903b 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -1,6 +1,6 @@import abcimport uuid-from collections.abc import Callable+from collections.abc import Callable, Sequencefrom dataclasses import dataclassfrom datetime import datetimefrom functools import partial@@ -37,13 +37,15 @@ from posthog.dataclasses import frozenfrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.deletion_targets import (COVERAGE_DOC,+ PERSONAL_DATA_TARGETS,+ DeletionTarget,_any_node_has,resolve_placements,surviving_rows_sql,sweep_clusters,)from posthog.models.event.deletion import events_data_tables-from posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLEfrom posthog.models.group.sql import GROUPS_TABLEfrom posthog.models.person.sql import (PERSON_DISTINCT_ID2_TABLE,@@ -99,6 +101,28 @@ class DeleteConfig(dagster.Config):return datetime.fromisoformat(self.timestamp)+# sharded_events_json is skipped until the events cluster is reliably reachable from the sweep.+# A run that resolves it inconsistently is worse than one that never tries: it creates the+# dictionary on a cluster it may not mutate, and reports an erasure that did not happen. Rows the+# table holds stay readable meanwhile, which is the cost this accepts; see COVERAGE_DOC.+# Remove it from the default to sweep the table again. `skip_targets: []` in run config does the+# same for one run, without a deploy.+_DEFAULT_SKIP_TARGETS = [EVENTS_JSON_DATA_TABLE]+++class SweepTargetsConfig(dagster.Config):+ skip_targets: list[str] = pydantic.Field(+ default_factory=lambda: list(_DEFAULT_SKIP_TARGETS),+ description="Deletion targets to leave out of this run, named by either their storage or "+ 'their read table, e.g. ["sharded_events_json"] or ["events_json"]. A skipped target gets '+ "no dictionary, no mutation and no survivor count, and a cluster only it lives on is not "+ "addressed at all. Its rows stay readable while the requests covering them are still "+ "marked verified, so only skip a target whose rows you accept leaving in place. An "+ "unrecognised name fails the run rather than silently sweeping every target. Defaults to "+ '["sharded_events_json"]; pass [] to sweep every registered target.',+ )++class MonthlyCleanupConfig(dagster.Config):team_ids: list[int] = pydantic.Field(default_factory=lambda: [@@ -401,6 +425,52 @@ def ensure_no_concurrent_deletes_run(context: dagster.OpExecutionContext) -> Non)+def resolve_sweep_targets(context: dagster.OpExecutionContext, config: SweepTargetsConfig) -> list[str]:+ """The storage tables this run sweeps, decided once and handed to every op that dispatches.++ One decision rather than one per op: a sweep that creates a dictionary for a target it never+ mutates, or counts one it never swept, reports an erasure it did not perform. Returned as table+ names because the op boundary serializes them.++ Either name identifies a target, because an operator reaching for this mid-incident has the one+ from whichever error is in front of them, and a target's storage and read tables differ.+ """+ skipped = set(config.skip_targets)+ known = {name for target in PERSONAL_DATA_TARGETS for name in (target.data_table, target.read_table)}+ if unknown := skipped - known:+ raise dagster.Failure(+ description=f"unknown skip_targets: {sorted(unknown)}. Known names: {sorted(known)}. "+ f"Refusing rather than sweeping a target that was meant to be skipped."+ )++ swept = [+ target.data_table+ for target in PERSONAL_DATA_TARGETS+ if target.data_table not in skipped and target.read_table not in skipped+ ]+ left = [target.data_table for target in PERSONAL_DATA_TARGETS if target.data_table not in swept]++ context.add_output_metadata(+ {+ "swept_tables": dagster.MetadataValue.json(swept),+ "skipped_tables": dagster.MetadataValue.json(left),+ }+ )+ if left:+ context.log.warning(+ f"Leaving rows in place on {', '.join(left)}: skipped by config, and the requests "+ f"covering those rows are still marked verified. See {COVERAGE_DOC}."+ )+ return swept+++def _targets_named(data_tables: Sequence[str]) -> tuple[DeletionTarget, ...]:+ """The registered targets whose storage table is listed, in registration order."""+ wanted = set(data_tables)+ return tuple(target for target in PERSONAL_DATA_TARGETS if target.data_table in wanted)++@dagster.op(ins={"start_after": dagster.In(dagster.Nothing)})def get_oldest_person_override_timestamp(cluster: dagster.ResourceParam[ClickhouseCluster],@@ -488,6 +558,7 @@ def load_pending_deletions(def create_deletes_dict(context: dagster.OpExecutionContext,load_pending_deletions: PendingDeletesTable,+ swept_targets: list[str],config: DeleteConfig,cluster: dagster.ResourceParam[ClickhouseCluster],) -> PendingDeletesDictionary:@@ -506,7 +577,7 @@ def create_deletes_dict(create_on_every_cluster(context,- sweep_clusters(cluster),+ sweep_clusters(cluster, _targets_named(swept_targets)),del_dict,shards=config.shards,max_execution_time=config.max_execution_time,@@ -518,6 +589,7 @@ def create_deletes_dict(@dagster.opdef create_adhoc_event_deletes_dict(context: dagster.OpExecutionContext,+ swept_targets: list[str],config: DeleteConfig,cluster: dagster.ResourceParam[ClickhouseCluster],) -> AdhocEventDeletesDictionary:@@ -538,7 +610,7 @@ def create_adhoc_event_deletes_dict(create_on_every_cluster(context,- sweep_clusters(cluster),+ sweep_clusters(cluster, _targets_named(swept_targets)),del_dict,shards=config.shards,max_execution_time=config.max_execution_time,@@ -567,9 +639,10 @@ def create_adhoc_event_deletes_dict(def load_and_verify_deletes_dictionary(cluster: dagster.ResourceParam[ClickhouseCluster],dictionary: PendingDeletesDictionary,+ swept_targets: list[str],) -> PendingDeletesDictionary:"""Load the dictionary on every host of every cluster the mutations run on, and verify it."""- load_and_verify_on_every_cluster(sweep_clusters(cluster), dictionary)+ load_and_verify_on_every_cluster(sweep_clusters(cluster, _targets_named(swept_targets)), dictionary)return dictionary@@ -577,9 +650,10 @@ def load_and_verify_deletes_dictionary(def load_and_verify_adhoc_event_deletes_dictionary(cluster: dagster.ResourceParam[ClickhouseCluster],dictionary: AdhocEventDeletesDictionary,+ swept_targets: list[str],) -> AdhocEventDeletesDictionary:"""Load the dictionary on every host of every cluster the mutations run on, and verify it."""- load_and_verify_on_every_cluster(sweep_clusters(cluster), dictionary)+ load_and_verify_on_every_cluster(sweep_clusters(cluster, _targets_named(swept_targets)), dictionary)return dictionary@@ -589,6 +663,7 @@ def delete_events(cluster: dagster.ResourceParam[ClickhouseCluster],load_and_verify_deletes_dictionary: PendingDeletesDictionary,load_and_verify_adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary,+ swept_targets: list[str],) -> tuple[PendingDeletesDictionary, ClusterShardMutations]:"""Delete events from every personal-data table, on whichever cluster stores each one."""@@ -630,8 +705,8 @@ def delete_events(})- # Every registered target must get this delete, or rows survive on the table that got skipped.- placements = resolve_placements(cluster)+ # Every target this run sweeps must get the delete, or rows survive on the one that missed it.+ placements = resolve_placements(cluster, _targets_named(swept_targets))reuse_floor = _mutation_reuse_floor(cluster)delete_mutation_runners = [(@@ -913,6 +988,7 @@ def _count_through(def _count_unswept_rows(context: dagster.OpExecutionContext,cluster: ClickhouseCluster,+ targets: Sequence[DeletionTarget],pending_deletes_dictionary: "PendingDeletesDictionary",adhoc_event_deletes_dictionary: "AdhocEventDeletesDictionary",max_execution_time: int,@@ -936,7 +1012,7 @@ def _count_unswept_rows("""params = _delete_predicate_params(pending_deletes_dictionary, adhoc_event_deletes_dictionary)counts: dict[str, int | None] = {}- for placement in resolve_placements(cluster):+ for placement in resolve_placements(cluster, targets):counts[placement.target.read_table] = _count_through(context,partial(_rows_from_any_host, cluster),@@ -968,6 +1044,7 @@ def _count_unswept_rows(@dagster.opdef mark_deletions_verified(context: dagster.OpExecutionContext,+ swept_targets: list[str],config: DeleteConfig,cluster: dagster.ResourceParam[ClickhouseCluster],pending_deletions_dictionary: PendingDeletesDictionary,@@ -976,6 +1053,7 @@ def mark_deletions_verified(unswept = _count_unswept_rows(context,cluster,+ _targets_named(swept_targets),pending_deletions_dictionary,adhoc_event_deletes_dictionary,config.verification_max_execution_time,@@ -1030,6 +1108,7 @@ def mark_deletions_verified(@dagster.opdef cleanup_delete_assets(cluster: dagster.ResourceParam[ClickhouseCluster],+ swept_targets: list[str],config: DeleteConfig,resources: VerifiedDeletionResources,) -> bool:@@ -1041,7 +1120,7 @@ def cleanup_delete_assets(# Must drop dict first. Every cluster the mutations ran on carries a copy of each dictionary;# only the job's own cluster carries the source table the staged object was exported from.- for handle in sweep_clusters(cluster):+ for handle in sweep_clusters(cluster, _targets_named(swept_targets)):handle.map_all_hosts(resources.pending_deletions_dictionary.drop).result()handle.map_all_hosts(resources.adhoc_event_deletes_dictionary.drop).result()@@ -1066,12 +1145,17 @@ def deletes_job():"""Job that handles deletion of events."""# Prepare requested deletions dataoldest_override_timestamp = get_oldest_person_override_timestamp(start_after=ensure_no_concurrent_deletes_run())+ swept_targets = resolve_sweep_targets()deletions_table = load_pending_deletions(create_pending_deletions_table(oldest_override_timestamp))- pending_deletes_dictionary = load_and_verify_deletes_dictionary(create_deletes_dict(deletions_table))- adhoc_event_deletes_dictionary = load_and_verify_adhoc_event_deletes_dictionary(create_adhoc_event_deletes_dict())+ pending_deletes_dictionary = load_and_verify_deletes_dictionary(+ create_deletes_dict(deletions_table, swept_targets), swept_targets+ )+ adhoc_event_deletes_dictionary = load_and_verify_adhoc_event_deletes_dictionary(+ create_adhoc_event_deletes_dict(swept_targets), swept_targets+ )# Delete all data requested- delete_mutations = delete_events(pending_deletes_dictionary, adhoc_event_deletes_dictionary)+ delete_mutations = delete_events(pending_deletes_dictionary, adhoc_event_deletes_dictionary, swept_targets)pending_deletes_dictionary = wait_for_delete_mutations_in_shards(delete_mutations)document_mutations = delete_event_documents(pending_deletes_dictionary)pending_deletes_dictionary = wait_for_delete_mutations_in_shards.alias("wait_for_document_delete_mutations")(@@ -1092,10 +1176,12 @@ def deletes_job():delete_mutations = delete_team_data_from(table)(pending_deletes_dictionary)pending_deletes_dictionary = wait_for_delete_mutations_in_all_hosts(delete_mutations)- verified_deletion_resources = mark_deletions_verified(pending_deletes_dictionary, adhoc_event_deletes_dictionary)+ verified_deletion_resources = mark_deletions_verified(+ swept_targets, pending_deletes_dictionary, adhoc_event_deletes_dictionary+ )# Clean up- cleanup_delete_assets(verified_deletion_resources)+ cleanup_delete_assets(swept_targets, verified_deletion_resources)# What every sensor-launched deletes_job run carries. retry_max_attempts is raised becausediff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex 362c582efc10..89aea3a5a966 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -36,12 +36,13 @@ from posthog.dags.deletes import (manual_deletes_job,mark_deletions_verified,monthly_old_events_cleanup_job,+ resolve_sweep_targets,run_deletes_after_manual_trigger,)from posthog.dags.person_overrides import squash_person_overridesfrom posthog.dags.tests.conftest import insert_flag_evaluationsfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.deletion_targets import EVENTS, TargetPlacement+from posthog.models.deletion_targets import EVENTS, PERSONAL_DATA_TARGETS, TargetPlacementfrom posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE@@ -1034,7 +1035,7 @@ def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: Clickhcontext = build_op_context()before = _count_unswept_rows(- context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time+ context, cluster, PERSONAL_DATA_TARGETS, dictionary, adhoc, DeleteConfig().verification_max_execution_time)surviving = before["events"]assert surviving is not None and surviving >= 2, "the count cannot see rows the sweep has not removed yet"@@ -1047,14 +1048,18 @@ def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: Clickhfor _host, mutation in cluster.map_one_host_per_shard(runner).result().items():cluster.map_all_hosts(mutation.wait).result()- after = _count_unswept_rows(context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time)+ after = _count_unswept_rows(+ context, cluster, PERSONAL_DATA_TARGETS, dictionary, adhoc, DeleteConfig().verification_max_execution_time+ )assert after["events"] == 0# A row ingested after its request was created is outside that request's scope, so it# must fail neither the delete nor the verification: counting it would let one tenant# that keeps ingesting backdated events block every tenant's deletions from being marked.cluster.any_host_by_role(insert_late_event, NodeRole.DATA).result()- late = _count_unswept_rows(context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time)+ late = _count_unswept_rows(+ context, cluster, PERSONAL_DATA_TARGETS, dictionary, adhoc, DeleteConfig().verification_max_execution_time+ )assert late["events"] == 0, "a row inserted after its request's created_at must not count as unswept"assert cluster.any_host_by_role(count_late_event_rows, NodeRole.DATA).result() == 1, ("the created_at bound, not a delete, must be what hides the late row"@@ -1120,6 +1125,7 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(clustecounts = _count_unswept_rows(build_op_context(),cluster,+ PERSONAL_DATA_TARGETS,dictionary,adhoc,DeleteConfig().verification_max_execution_time,@@ -1133,6 +1139,99 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(clustecluster.any_host(table.drop).result()+def test_a_skipped_target_keeps_its_rows_while_the_rest_are_swept(cluster: ClickhouseCluster):+ # Seven ops resolve the sweep, and each one that misses the resolved list puts the run back to+ # sweeping a target the config took out. Only a dispatched mutation shows that from the+ # outside, so this asserts the one table that is skipped still holds its rows after a run that+ # deleted from the others.+ timestamp = (datetime.now() + timedelta(days=31)).replace(microsecond=0)+ queued_uuid, unqueued_uuid = 7001, 7002++ events = [(i, f"distinct_id_{i}", UUID(int=i), timestamp) for i in (queued_uuid, unqueued_uuid)]++ def insert_events(client: Client) -> None:+ client.execute(+ "INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp) VALUES",+ events,+ )++ def insert_adhoc_event_deletes(client: Client) -> None:+ client.execute(+ "INSERT INTO adhoc_events_deletion (team_id, uuid, created_at) VALUES",+ [(queued_uuid, UUID(int=queued_uuid), timestamp)],+ )++ def surviving_events(client: Client) -> set[tuple[int, UUID]]:+ result = client.execute(+ "SELECT team_id, uuid FROM events WHERE team_id IN %(teams)s AND _row_exists = 1",+ {"teams": [queued_uuid, unqueued_uuid]},+ )+ return {(row[0], row[1]) for row in result} if isinstance(result, list) else set()++ cluster.any_host(insert_events).result()+ cluster.any_host(+ partial(+ insert_flag_evaluations,+ [(i, f"distinct_id_{i}", UUID(int=i), UUID(int=i), timestamp) for i in (queued_uuid, unqueued_uuid)],+ )+ ).result()+ cluster.any_host(insert_adhoc_event_deletes).result()++ deletes_job.execute_in_process(+ run_config={+ "ops": {+ "create_pending_deletions_table": {"config": {"timestamp": timestamp.isoformat()}},+ "resolve_sweep_targets": {"config": {"skip_targets": ["sharded_flag_evaluations"]}},+ }+ },+ resources={"cluster": cluster},+ )++ surviving = cluster.any_host(surviving_events).result()+ assert (queued_uuid, UUID(int=queued_uuid)) not in surviving, "the swept target kept a queued uuid"+ assert (unqueued_uuid, UUID(int=unqueued_uuid)) in surviving, "the sweep removed a uuid nobody queued"++ flags = cluster.any_host(surviving_flag_evaluations).result()+ assert (queued_uuid, UUID(int=queued_uuid), UUID(int=queued_uuid)) in flags, "the skipped target was swept anyway"+++ "skip_targets,expected",+ [+ ([], ["sharded_events", "sharded_events_json", "sharded_flag_evaluations"]),+ (["sharded_events_json"], ["sharded_events", "sharded_flag_evaluations"]),+ (["events_json"], ["sharded_events", "sharded_flag_evaluations"]),+ (["events_json", "sharded_flag_evaluations"], ["sharded_events"]),+ ],+ ids=["nothing_skipped", "by_storage_table", "by_read_table", "two_targets"],+)+def test_skip_targets_drops_a_target_named_by_either_of_its_tables(skip_targets, expected) -> None:+ # An operator reaches for this from whichever error is in front of them, which carries the+ # storage table on a mutation and the read table on a survivor count. Accepting only one of the+ # two would read as a working skip while the target kept being swept.+ context = build_op_context(config={"skip_targets": skip_targets})++ assert resolve_sweep_targets(context) == expected+++def test_events_json_is_skipped_by_default() -> None:+ # The events cluster is not reliably reachable from the sweep, and a run that resolves it+ # inconsistently reports an erasure it did not perform. Dropping the default would resume that+ # sweep silently, because nothing else in a run says which targets it was supposed to reach.+ assert resolve_sweep_targets(build_op_context()) == ["sharded_events", "sharded_flag_evaluations"]+++def test_an_unrecognised_skip_target_fails_the_run() -> None:+ # A typo would otherwise widen the sweep back to every target, which is the dangerous+ # direction: the run reports success having deleted from a table that was meant to be left+ # alone, and the requests covering those rows are marked verified either way.+ context = build_op_context(config={"skip_targets": ["sharded_event_json"]})++ with pytest.raises(dagster.Failure, match="unknown skip_targets"):+ resolve_sweep_targets(context)++@pytest.mark.parametrize("unswept",[@@ -1147,6 +1246,7 @@ def test_marking_is_refused_when_a_count_survives_or_cannot_complete(unswept: diwith pytest.raises(dagster.Failure) as excinfo:mark_deletions_verified(build_op_context(),+ [target.data_table for target in PERSONAL_DATA_TARGETS],DeleteConfig(),cast(ClickhouseCluster, None),PendingDeletesDictionary(source=PendingDeletesTable(timestamp=datetime(2026, 9, 1))),