Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): reach flag_evaluations via event uuids when deferred (#114745)

Phil Haacka7ddbfe5f96f
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index d891e0af22d9..412cb59dc984 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -95,7 +95,7 @@ Leaving one out stays possible, and `PERSON_ID_REWRITE_EXEMPT` is where that dec
- `sharded_events` — all sweeps.
- `sharded_events_json` — all sweeps, on the events cluster, through patch parts instead of mutations (`uses_patch_parts`). Optional: only present after the native-JSON migration.
-- `sharded_flag_evaluations` — person, team, queued-uuid, immediate and deferred event removal, and property removal of event and person properties (below). Neither event removal nor property removal sweeps it when the request carries a HogQL predicate. Optional.
+- `sharded_flag_evaluations` — person, team, queued-uuid, immediate and deferred event removal, and property removal of event and person properties (below). Immediate event removal skips it when the request carries a HogQL predicate. Deferred event removal with a predicate reaches only the rows that have an events copy (below). Property removal with a predicate does not sweep it. 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.
Native property-removal requests fail when the selected rows retain a requested permanent or temporary property, or a matching person `$set`/`$set_once` instruction.
@@ -218,18 +218,44 @@ The job finds typed columns through their comments in `system.columns`, not thro
`get_event_removal_shards` leaves `flag_evaluations` out of an immediate request that carries a HogQL predicate, so the request neither sweeps the table nor checks it for matching rows.
The rows age out with the table's TTL. The table partitions by month with `ttl_only_drop_parts = 1`, so a part drops only once its newest row expires: the real wait is up to about 120 days, not the 90-day TTL.
The skip exists because of the HogQL gap below: without it, the gate refuses every immediate request with a predicate whose team has matching `$feature_flag_called` rows.
+The events copies that a deferred request deletes through do not help here, because the immediate path deletes the events rows without queueing their uuids.
An immediate request without a predicate sweeps the table and verifies it like the events tables, because its delete predicate names only `team_id`, `timestamp` and `event`.
-### Event removal with a HogQL predicate does not reach `flag_evaluations`
+### Event removal with a HogQL predicate reaches `flag_evaluations` only through events copies
`compile_hogql_predicate` resolves every predicate against the events HogQL table and emits events-specific physical columns.
Its only axis of variation is legacy vs native-JSON events, so while the dag does compile one fragment per target, no target selects a different table root.
Whether a given fragment would run against `flag_evaluations` depends on the predicate and the team's modifiers: one naming only `event` or `distinct_id` would, one reaching a `mat_*` column or a property-group map would not, and nothing validates which.
The dag does not guess.
It never runs a fragment against the table.
-A deferred request with a predicate is refused if the table holds matching rows, and an immediate one skips the table (above).
+An immediate request with a predicate skips the table (above).
A HogQL table definition for `flag_evaluations` does not change that, because nothing routes compilation to a table.
+
+A deferred request with a predicate reaches the table through `events` instead.
+A flag-evaluation row is a fork of its `$feature_flag_called` event, with the same uuid, and both tables shard on `sipHash64(distinct_id)`, so the two copies share a shard.
+`DeletionTarget.copied_from` records that relationship.
+The queue fill reads uuids from `sharded_events` with the full predicate, and the drain deletes those uuids from every target, so it deletes the flag row of every event the predicate names.
+A flag row whose event the predicate does not name keeps its events copy and stays.
+
+That only works for a row that has an events copy.
+An org on `flag_evaluations_mode` 2 stores its flag calls only in `flag_evaluations`, and a deletion that skipped the table can leave a flag row whose event is gone.
+The gate therefore counts the matching rows that have no copy in `sharded_events`, shard-locally, and refuses the request when it finds any.
Requests without a predicate, immediate or deferred, are swept normally.
+A deferred one reads the table's own uuids into the queue.
+
+Verification of a deferred request with a predicate, when the table holds rows in the request's window, makes two counts: the request's queue rows that the drain has not marked deleted, and the table's rows with no copy in `sharded_events`.
+The queue rows hold the request until `deletes_job` drains them, including a queued row whose event a property removal changed so that the predicate no longer matches it.
+The rows with no copy hold the request after the drain.
+A flag row stamped after its uuid was queued falls outside the drain's `inserted_at` bound, so it survives the drain.
+The drain still deletes its events copy.
+The rows with no copy therefore include it and keep the request in QUEUED.
+A re-filed request does not reach that row.
+The gate refuses one with the predicate, because the row has no events copy.
+A deferred one without the predicate queues the uuid, but the drain skips it while the first drain's `is_deleted` marker lasts, which is 3 months.
+Only an immediate request without the predicate deletes the row, and it also deletes every other row in its window that its event filter names.
+The verify sweep therefore keeps checking a deferred request with a predicate for `lookback_days` after its window falls behind the table's TTL horizon, so the request moves to COMPLETED once the TTL drops the row.
+The rows with no copy also keep a request the gate refused, which queued nothing, from passing verification as a FAILED request.
+Counting every row that matches the request's other criteria would hold the request in QUEUED until the TTL, whenever the team has flag calls the predicate does not name.
## Producer prerequisite: person_id parity
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 74c760f93d59..886e628dcfc2 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -53,6 +53,9 @@ from posthog.models.data_deletion_request import (
event_removal_where,
jsonhas_expr,
portable_event_removal_where,
+ queued_requests_to_verify,
+ reaches_target_through_event_uuids,
+ rows_without_events_copy_criteria,
verify_queued_request,
)
from posthog.models.deletion_targets import (
@@ -66,6 +69,7 @@ from posthog.models.deletion_targets import (
UnsweptRowsError,
assert_no_unsweepable_rows,
assert_sweep_complete,
+ count_surviving_rows,
placement_for,
resolve_placements,
surviving_rows_sql,
@@ -532,6 +536,14 @@ _HOGQL_UNSWEEPABLE_REASON = (
f"table never stores. See {COVERAGE_DOC}."
)
+_HOGQL_NO_EVENTS_COPY_REASON = (
+ "the request carries a HogQL predicate, which only compiles against the events schema, and these "
+ "rows have no copy in the events table. The deferred queue deletes rows here through the uuids of "
+ "their events copies, so it cannot decide whether the predicate names these rows. Such rows belong to an "
+ "org whose flag calls are stored only in this table, or to events an earlier deletion removed without "
+ f"these rows. To proceed, re-file the request without the predicate. See {COVERAGE_DOC}."
+)
+
def _refuse_unsweepable(
cluster: ClickhouseCluster,
@@ -556,6 +568,10 @@ def _refuse_unsweepable(
raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc
+def _same_criteria(criteria: tuple[str, dict]) -> Callable[[DeletionTarget], tuple[str, dict]]:
+ return lambda _target: criteria
+
+
def _deletion_target(data_table: str) -> DeletionTarget:
return next(target for target in PERSONAL_DATA_TARGETS if target.data_table == data_table)
@@ -638,11 +654,27 @@ def _event_removal_placements(
return placements
unsweepable = [p.target for p in placements if not p.target.accepts_hogql_predicate]
- if unsweepable:
- criteria = portable_event_removal_where(deletion_request)
- _refuse_unsweepable(
- cluster, unsweepable, deletion_request, lambda _target: criteria, reason=_HOGQL_UNSWEEPABLE_REASON
- )
+ criteria = portable_event_removal_where(deletion_request)
+ reachable = [t for t in unsweepable if reaches_target_through_event_uuids(deletion_request, t)]
+
+ _refuse_unsweepable(
+ cluster,
+ [t for t in unsweepable if t not in reachable],
+ deletion_request,
+ _same_criteria(criteria),
+ reason=_HOGQL_UNSWEEPABLE_REASON,
+ )
+ # The copy check reads the uuid of every matching event, so it runs only on tables that hold rows
+ # in the request's window.
+ for target in [t for t in reachable if count_surviving_rows(cluster, t, *criteria)]:
+ for window_criteria in rows_without_events_copy_criteria(deletion_request, target):
+ _refuse_unsweepable(
+ cluster,
+ [target],
+ deletion_request,
+ _same_criteria(window_criteria),
+ reason=_HOGQL_NO_EVENTS_COPY_REASON,
+ )
return [p for p in placements if p.target.accepts_hogql_predicate]
@@ -2324,18 +2356,16 @@ def data_deletion_request_pickup_sensor(context: dagster.SensorEvaluationContext
class VerifyQueuedConfig(dagster.Config):
lookback_days: int = pydantic.Field(
default=28,
- description="Only verify QUEUED requests created within this many days. Bounds the sweep so a "
- "permanently stuck request isn't re-checked forever.",
+ description="Only verify QUEUED requests created within this many days. A deferred event removal "
+ "with a HogQL predicate is also verified for this many days after its window falls behind the "
+ "flag_evaluations TTL. Bounds the sweep so a permanently stuck request isn't re-checked forever.",
)
@dagster.op(tags=OWNER_TAG)
def verify_queued_deletion_requests_op(context: dagster.OpExecutionContext, config: VerifyQueuedConfig) -> None:
"""Verify recently-QUEUED deletion requests and promote those whose events are gone."""
- from django.utils import timezone
-
- cutoff = timezone.now() - timedelta(days=config.lookback_days)
- queued = DataDeletionRequest.objects.filter(status=RequestStatus.QUEUED, created_at__gte=cutoff)
+ queued = queued_requests_to_verify(timedelta(days=config.lookback_days))
promoted = 0
still_queued = 0
for request in queued:
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index b9740d7fc49c..79b61362f88d 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -858,16 +858,24 @@ def test_verify_queued_job_promotes_in_window_and_skips_old(cluster: ClickhouseC
recent = DataDeletionRequest.objects.create(**common)
old = DataDeletionRequest.objects.create(**common)
- # created_at uses auto_now_add, so push `old` outside the default 28-day window via update().
- DataDeletionRequest.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=60))
+ old_hogql, _ = _deferred_hogql_flag_request("test-verify-queued-hogql")
+ old_hogql_past_ttl, _ = _deferred_hogql_flag_request("test-verify-queued-hogql-past-ttl")
+ DataDeletionRequest.objects.filter(pk=old_hogql_past_ttl.pk).update(
+ start_time=now - timedelta(days=400), end_time=now - timedelta(days=300)
+ )
+ DataDeletionRequest.objects.filter(pk__in=[old.pk, old_hogql.pk, old_hogql_past_ttl.pk]).update(
+ created_at=timezone.now() - timedelta(days=60)
+ )
result = verify_queued_deletion_requests_job.execute_in_process()
assert result.success
- recent.refresh_from_db()
- old.refresh_from_db()
+ for request in (recent, old, old_hogql, old_hogql_past_ttl):
+ request.refresh_from_db()
assert recent.status == RequestStatus.COMPLETED
assert old.status == RequestStatus.QUEUED
+ assert old_hogql.status == RequestStatus.COMPLETED
+ assert old_hogql_past_ttl.status == RequestStatus.QUEUED
def test_verify_queued_job_registered_in_clickhouse_location():
@@ -2063,6 +2071,7 @@ def _request_context(request: DataDeletionRequest) -> DeletionRequestContext:
properties=request.properties,
person_properties=list(request.person_properties or []),
delete_all_events=request.delete_all_events,
+ execution_mode=request.execution_mode,
hogql_predicate=request.hogql_predicate or "",
inserted_at_marker=request.property_removal_marker,
)
@@ -2560,6 +2569,128 @@ def test_deferred_event_removal_queues_flag_evaluations_and_blocks_promotion(clu
cluster.any_host(_truncate_adhoc_events_deletion).result()
+def _delete_uuid(table: str, uuid: UUID, client: Client) -> None:
+ client.execute(
+ f"DELETE FROM {table} WHERE uuid = %(uuid)s", {"uuid": uuid}, settings={"lightweight_deletes_sync": 2}
+ )
+
+
+def _deferred_hogql_flag_request(name: str) -> tuple[DataDeletionRequest, DeletionRequestContext]:
+ from posthog.models.organization import Organization
+ from posthog.models.team import Team
+
+ team = Team.objects.create(organization=Organization.objects.create(name=name), name=name)
+ now = datetime.now(UTC)
+ request = DataDeletionRequest.objects.create(
+ team_id=team.id,
+ request_type=RequestType.EVENT_REMOVAL,
+ delete_all_events=True,
+ start_time=now - timedelta(days=14),
+ end_time=now + timedelta(minutes=1),
+ hogql_predicate="properties.$browser = 'Chrome'",
+ status=RequestStatus.QUEUED,
+ execution_mode=ExecutionMode.DEFERRED.value,
+ )
+ return request, _request_context(request)
+
+
+def test_deferred_event_removal_with_a_hogql_predicate_reaches_flag_evaluations_through_event_uuids(
+ cluster: ClickhouseCluster,
+) -> None:
+ from posthog.models.data_deletion_request import verify_queued_request
+
+ request, ctx = _deferred_hogql_flag_request("test-deferred-hogql-flag-copies")
+ now = datetime.now(UTC)
+ earlier = now - timedelta(days=10)
+ chrome, firefox, earlier_chrome = uuid4(), uuid4(), uuid4()
+ cluster.any_host(_truncate_adhoc_events_deletion).result()
+ cluster.any_host(_truncate_flag_evaluations).result()
+ cluster.any_host(
+ partial(
+ _insert_events_with_properties,
+ [
+ (ctx.team_id, FLAG_EVALUATIONS_SOURCE_EVENT, chrome, now, '{"$browser": "Chrome"}'),
+ (ctx.team_id, FLAG_EVALUATIONS_SOURCE_EVENT, firefox, now, '{"$browser": "Firefox"}'),
+ (ctx.team_id, FLAG_EVALUATIONS_SOURCE_EVENT, earlier_chrome, earlier, '{"$browser": "Chrome"}'),
+ ],
+ )
+ ).result()
+ cluster.any_host(
+ partial(
+ _insert_flag_evaluations_with_properties,
+ [
+ (ctx.team_id, "", '{"$browser": "Chrome"}', str(chrome), now, now),
+ (ctx.team_id, "", '{"$browser": "Firefox"}', str(firefox), now, now),
+ (ctx.team_id, "", '{"$browser": "Chrome"}', str(earlier_chrome), earlier, earlier),
+ ],
+ )
+ ).result()
+
+ try:
+ _run_event_deletion(cluster, ctx)
+ assert cluster.any_host(partial(_adhoc_pending_uuids, ctx.team_id)).result() == {chrome, earlier_chrome}
+
+ # The queued events no longer match the predicate, so only their queued uuids hold the request.
+ for queued_uuid in (chrome, earlier_chrome):
+ cluster.any_host(partial(_delete_uuid, EVENTS_DATA_TABLE(), queued_uuid)).result()
+ cluster.any_host(
+ partial(
+ _insert_events_with_properties,
+ [
+ (ctx.team_id, FLAG_EVALUATIONS_SOURCE_EVENT, chrome, now, "{}"),
+ (ctx.team_id, FLAG_EVALUATIONS_SOURCE_EVENT, earlier_chrome, earlier, "{}"),
+ ],
+ )
+ ).result()
+ outcome = verify_queued_request(request)
+ assert outcome.remaining == 2
+ assert outcome.promoted is False
+
+ # Emptying the queue stands in for the drain marking the queued uuids deleted. From here on only
+ # flag rows with no events copy hold the request.
+ cluster.any_host(_truncate_adhoc_events_deletion).result()
+ cluster.any_host(partial(_delete_uuid, EVENTS_DATA_TABLE(), chrome)).result()
+ assert verify_queued_request(request).promoted is False
+
+ cluster.any_host(partial(_delete_uuid, FLAG_EVALUATIONS_DATA_TABLE, chrome)).result()
+ cluster.any_host(partial(_delete_uuid, EVENTS_DATA_TABLE(), earlier_chrome)).result()
+ assert verify_queued_request(request).promoted is False
+
+ cluster.any_host(partial(_delete_uuid, FLAG_EVALUATIONS_DATA_TABLE, earlier_chrome)).result()
+ assert verify_queued_request(request).promoted is True
+ finally:
+ cluster.any_host(_truncate_adhoc_events_deletion).result()
+ cluster.any_host(_truncate_flag_evaluations).result()
+
+
+def test_deferred_event_removal_with_a_hogql_predicate_refuses_flag_rows_without_an_event(
+ cluster: ClickhouseCluster,
+) -> None:
+ from posthog.models.data_deletion_request import verify_queued_request
+
+ request, ctx = _deferred_hogql_flag_request("test-deferred-hogql-flag-no-copy")
+ earlier = datetime.now(UTC) - timedelta(days=10)
+ cluster.any_host(_truncate_flag_evaluations).result()
+ cluster.any_host(
+ partial(
+ _insert_flag_evaluations_with_properties,
+ [(ctx.team_id, "", '{"$browser": "Chrome"}', str(uuid4()), earlier, earlier)],
+ )
+ ).result()
+
+ try:
+ with pytest.raises(dagster.Failure, match="have no copy in the events table"):
+ _run_event_deletion(cluster, ctx)
+
+ request.status = RequestStatus.FAILED
+ request.save(update_fields=["status"])
+ assert verify_queued_request(request).promoted is False
+ finally:
+ cluster.any_host(_truncate_flag_evaluations).result()
+
+
@pytest.mark.django_db
def test_get_property_removal_shards_refuses_a_hogql_predicate_when_flag_evaluations_holds_matching_rows(
cluster: ClickhouseCluster,
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index c73f41c093f7..779ec0dce89e 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -1,6 +1,9 @@
from collections.abc import Callable
from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING
+from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.cache import cache
from django.core.exceptions import ValidationError
@@ -10,6 +13,9 @@ from django.utils import timezone
from posthog.models.utils import UUIDModel
+if TYPE_CHECKING:
+ from posthog.models.deletion_targets import DeletionTarget
+
def jsonhas_expr(prop: str, param_prefix: str, column: str = "properties") -> str:
"""Build a ClickHouse ``JSONHas`` expression for a (possibly nested) property path.
@@ -23,6 +29,10 @@ def jsonhas_expr(prop: str, param_prefix: str, column: str = "properties") -> st
return f"JSONHas({column}, {args})"
+def _hogql_predicate_text(obj) -> str:
+ return (getattr(obj, "hogql_predicate", "") or "").strip()
+
+
def compile_hogql_predicate(obj, use_new_events_schema: bool = False) -> tuple[str, dict]:
"""Parse and compile ``obj.hogql_predicate`` into a ClickHouse SQL fragment.
@@ -44,7 +54,7 @@ def compile_hogql_predicate(obj, use_new_events_schema: bool = False) -> tuple[s
JSONExtract/materialized-column reads. Deletions target both physical events tables, so
callers compile one fragment per table.
"""
- predicate = (getattr(obj, "hogql_predicate", "") or "").strip()
+ predicate = _hogql_predicate_text(obj)
if not predicate:
return "", {}
@@ -141,7 +151,7 @@ def cached_compile_hogql_predicate(obj) -> tuple[str, dict]:
Only the informational admin path should use this. The Dagster deletion job compiles fresh via
``compile_hogql_predicate`` so the mutation is never built from a stale fragment.
"""
- predicate = (getattr(obj, "hogql_predicate", "") or "").strip()
+ predicate = _hogql_predicate_text(obj)
if not predicate:
return "", {}
request_id = getattr(obj, "pk", None) or getattr(obj, "request_id", None)
@@ -202,6 +212,78 @@ def portable_event_removal_where(obj) -> tuple[str, dict]:
return " ".join(p for p in parts if p), event_match_params(obj)
+def reaches_target_through_event_uuids(obj, target: "DeletionTarget") -> bool:
+ """Whether ``obj`` deletes ``target``'s rows through the uuids of their events copies.
+
+ A deferred request queues the uuids of the events its HogQL predicate matches, and the drain
+ deletes those uuids from every target. That is how the predicate, which only compiles against
+ events, reaches a target that holds copies of events.
+ """
+ return (
+ target.copied_from is not None
+ and bool(_hogql_predicate_text(obj))
+ and obj.execution_mode == ExecutionMode.DEFERRED
+ )
+
+
+# With ttl_only_drop_parts and monthly partitions, a part drops only once its newest row expires, so
+# a row can outlive the TTL by up to a month.
+_TTL_HORIZON_SLACK_DAYS = 33
+
+# The copy subquery holds the uuid of every events copy in its window in memory on each shard.
+_COPY_CHECK_WINDOW = timedelta(days=7)
+
+
+def _ttl_horizon(target: "DeletionTarget") -> datetime | None:
+ """The oldest timestamp at which ``target`` can still hold a row, or None when it has no TTL."""
+ if target.ttl_days is None:
+ return None
+ return timezone.now() - timedelta(days=target.ttl_days + _TTL_HORIZON_SLACK_DAYS)
+
+
+def rows_without_events_copy_criteria(obj, target: "DeletionTarget") -> list[tuple[str, dict]]:
+ """``portable_event_removal_where`` narrowed to the rows of ``target`` with no copy in ``target.copied_from``.
+
+ A deferred removal deletes every other row through the uuid of its events copy, so these are the
+ only rows of ``target`` that a HogQL predicate cannot reach.
+
+ Returns one ``(predicate, params)`` pair per window of ``obj``'s range. A row and its events copy
+ carry the same timestamp, so a window holds the copies of its own rows. The range before the TTL
+ horizon stays one window, because the copy subquery reads no events there. The range after now
+ stays one window too, because few events carry a future timestamp.
+ """
+ assert target.copied_from is not None
+ predicate, params = portable_event_removal_where(obj)
+ # A copy that a lightweight delete hid counts as missing, as in surviving_rows_sql.
+ copies = f"{_EVENT_REMOVAL_TIME_PREDICATE} AND _row_exists = 1"
+ horizon = _ttl_horizon(target)
+ if horizon is not None:
+ # The target holds no row older than its TTL horizon. A row older than the bound reads as
+ # having no copy, which refuses or holds the request.
+ copies += " AND timestamp >= %(ttl_horizon)s"
+ params["ttl_horizon"] = horizon
+ if target.stored_events is not None:
+ copies += " AND event IN %(copied_events)s"
+ params["copied_events"] = sorted(target.stored_events)
+ # The subquery names the storage table rather than its Distributed proxy, so each shard compares
+ # its rows against its own events. That finds every copy only because a copy shares its row's shard.
+ predicate += (
+ f" AND uuid NOT IN (SELECT uuid FROM {settings.CLICKHOUSE_DATABASE}.{target.copied_from} WHERE {copies})"
+ )
+
+ start, end = obj.start_time, obj.end_time
+ windows = []
+ if horizon is not None and start < horizon:
+ windows.append((start, min(horizon, end)))
+ start = horizon
+ while start < min(end, timezone.now()):
+ windows.append((start, min(start + _COPY_CHECK_WINDOW, end)))
+ start += _COPY_CHECK_WINDOW
+ if start < end:
+ windows.append((start, end))
+ return [(predicate, {**params, "start_time": s, "end_time": e}) for s, e in windows]
+
+
def event_removal_where(obj, use_new_events_schema: bool = False) -> tuple[str, dict]:
"""Full WHERE predicate + params for event-removal queries.
@@ -673,8 +755,6 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict, *, user_id: int
automatically via :class:`QueryTags`). The auto-approval sweep job has no
acting user and passes None.
"""
- from django.conf import settings as django_settings
-
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
@@ -706,7 +786,7 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict, *, user_id: int
workload=Workload.OFFLINE,
query_type="delete_part_count",
):
- cluster = django_settings.CLICKHOUSE_CLUSTER
+ cluster = settings.CLICKHOUSE_CLUSTER
# nosemgrep: clickhouse-fstring-param-audit (filter built from internal helpers; cluster from Django settings)
parts_result = sync_execute(
@@ -811,19 +891,52 @@ def refresh_deletion_stats(request: "DataDeletionRequest", *, user_id: int | Non
return stats
+def _count_via_sync_execute(team_id: int, sql: str, params: dict) -> int:
+ from posthog.clickhouse.client import sync_execute
+ from posthog.clickhouse.client.connection import ClickHouseUser
+ from posthog.clickhouse.workload import Workload
+
+ result = sync_execute(
+ sql, params, team_id=team_id, readonly=True, workload=Workload.OFFLINE, ch_user=ClickHouseUser.META
+ )
+ return int(result[0][0]) if result else 0
+
+
+def count_pending_hogql_event_removals(request: "DataDeletionRequest") -> int:
+ from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+ from posthog.clickhouse.workload import Workload
+
+ with tags_context(
+ product=Product.INTERNAL,
+ feature=Feature.DATA_DELETION,
+ team_id=request.team_id,
+ workload=Workload.OFFLINE,
+ query_type="data_deletion_request_verify_queued",
+ ):
+ return _count_via_sync_execute(
+ request.team_id,
+ f"SELECT count() FROM {ADHOC_EVENTS_DELETION_TABLE} FINAL "
+ "WHERE team_id = %(team_id)s AND data_deletion_request_id = %(request_id)s AND is_deleted = 0",
+ {"team_id": request.team_id, "request_id": str(request.pk)},
+ )
+
+
def count_remaining_matching_events(request: "DataDeletionRequest") -> int:
"""Count rows still matching an event-removal request's criteria in ClickHouse.
Counts across every default deletion target that could hold the named events. A request is only
complete once its rows are gone from every table that the scheduled deletion job sweeps.
- A target that cannot take the compiled HogQL fragment is counted with the portable predicate
- instead, which matches a superset. That can only hold a request in QUEUED, never promote one
- early. It also means a non-zero count is not proof that rows were missed: for a HogQL request
- the superset can match rows the predicate itself never would.
+ On a deferred request with a HogQL predicate, a target that cannot take the compiled fragment but
+ holds copies of events gets two counts. The first is the request's queue rows that the drain has
+ not marked deleted, because the drain deletes the target's rows through those uuids. The second
+ is the target's rows with no events copy, which the drain cannot reach. Any other target that
+ cannot take the fragment is counted with the portable predicate instead, which matches a
+ superset. That can only hold a request in QUEUED, never promote one early. It also means a
+ non-zero count is not proof that rows were missed: for a HogQL request the superset can match
+ rows the predicate itself never would.
"""
- from posthog.clickhouse.client import sync_execute
- from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.clickhouse.workload import Workload
from posthog.models.deletion_targets import (
@@ -832,6 +945,9 @@ def count_remaining_matching_events(request: "DataDeletionRequest") -> int:
surviving_rows_sql,
)
+ def count_rows(read_table: str, predicate: str, params: dict) -> int:
+ return _count_via_sync_execute(request.team_id, surviving_rows_sql(read_table, predicate), params)
+
events = [] if request.delete_all_events else request.events
total = 0
with tags_context(
@@ -845,18 +961,19 @@ def count_remaining_matching_events(request: "DataDeletionRequest") -> int:
if not target.may_hold_any_of(events):
continue
if target.accepts_hogql_predicate:
- predicate, params = event_removal_where(request, use_new_events_schema=target.uses_new_events_schema)
- else:
+ criteria = [event_removal_where(request, use_new_events_schema=target.uses_new_events_schema)]
+ elif reaches_target_through_event_uuids(request, target):
predicate, params = portable_event_removal_where(request)
- result = sync_execute(
- surviving_rows_sql(target.read_table, predicate),
- params,
- team_id=request.team_id,
- readonly=True,
- workload=Workload.OFFLINE,
- ch_user=ClickHouseUser.META,
- )
- total += int(result[0][0]) if result else 0
+ # The copy check reads the uuid of every matching event, so it runs only when the target holds
+ # rows in the request's window.
+ if not count_rows(target.read_table, predicate, params):
+ continue
+ # docs/internal/clickhouse-deletion-coverage.md says which count holds the request at each stage.
+ total += count_pending_hogql_event_removals(request)
+ criteria = rows_without_events_copy_criteria(request, target)
+ else:
+ criteria = [portable_event_removal_where(request)]
+ total += sum(count_rows(target.read_table, predicate, params) for predicate, params in criteria)
return total
@@ -880,8 +997,6 @@ def discover_affected_mat_columns(properties: list[str], table_column: str, tabl
if not properties:
return []
- from django.conf import settings as django_settings
-
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
@@ -896,7 +1011,7 @@ def discover_affected_mat_columns(properties: list[str], table_column: str, tabl
AND comment LIKE '%%column_materializer::%%'
AND comment NOT LIKE '%%column_materializer::elements_chain::%%'
""",
- {"database": django_settings.CLICKHOUSE_DATABASE, "table": table},
+ {"database": settings.CLICKHOUSE_DATABASE, "table": table},
readonly=True,
ch_user=ClickHouseUser.META,
)
@@ -963,8 +1078,6 @@ def count_remaining_property_events(request: "DataDeletionRequest") -> int:
The presence predicate is built for the legacy schema, so the native-JSON table is left to the
job's own verification.
"""
- from posthog.clickhouse.client import sync_execute
- from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.clickhouse.workload import Workload
from posthog.models.deletion_targets import (
@@ -999,15 +1112,7 @@ def count_remaining_property_events(request: "DataDeletionRequest") -> int:
predicate, params = _property_presence_where(
request, mat_cols, person_mat_cols, with_hogql=target.accepts_hogql_predicate
)
- result = sync_execute(
- surviving_rows_sql(target.read_table, predicate),
- params,
- team_id=request.team_id,
- readonly=True,
- workload=Workload.OFFLINE,
- ch_user=ClickHouseUser.META,
- )
- total += int(result[0][0]) if result else 0
+ total += _count_via_sync_execute(request.team_id, surviving_rows_sql(target.read_table, predicate), params)
return total
@@ -1025,32 +1130,6 @@ def count_remaining_for_request(request: "DataDeletionRequest") -> int | None:
return None
-def count_pending_hogql_event_removals(request: "DataDeletionRequest") -> int:
- from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
- from posthog.clickhouse.client import sync_execute
- from posthog.clickhouse.client.connection import ClickHouseUser
- from posthog.clickhouse.query_tagging import Feature, Product, tags_context
- from posthog.clickhouse.workload import Workload
-
- with tags_context(
- product=Product.INTERNAL,
- feature=Feature.DATA_DELETION,
- team_id=request.team_id,
- workload=Workload.OFFLINE,
- query_type="data_deletion_request_verify_queued",
- ):
- result = sync_execute(
- f"SELECT count() FROM {ADHOC_EVENTS_DELETION_TABLE} FINAL "
- "WHERE team_id = %(team_id)s AND data_deletion_request_id = %(request_id)s AND is_deleted = 0",
- {"team_id": request.team_id, "request_id": str(request.pk)},
- team_id=request.team_id,
- readonly=True,
- workload=Workload.OFFLINE,
- ch_user=ClickHouseUser.META,
- )
- return int(result[0][0]) if result else 0
-
-
@dataclass
class VerifyOutcome:
remaining: int
@@ -1084,6 +1163,33 @@ def verify_queued_request(request: "DataDeletionRequest") -> VerifyOutcome:
return VerifyOutcome(remaining=remaining, promoted=bool(promoted))
+def queued_requests_to_verify(lookback: timedelta) -> list["DataDeletionRequest"]:
+ """The QUEUED requests that the verify sweep checks.
+
+ The sweep checks a request for ``lookback`` after it is created. It also checks a request that
+ reaches a target through event uuids for ``lookback`` after the request's window falls behind
+ that target's TTL horizon. The target's rows with no events copy hold such a request until the
+ TTL drops them. docs/internal/clickhouse-deletion-coverage.md explains why a re-filed deferred
+ request does not delete them sooner.
+ """
+ from posthog.models.deletion_targets import DEFAULT_DELETION_TARGETS
+
+ created_after = timezone.now() - lookback
+ queued = DataDeletionRequest.objects.filter(status=RequestStatus.QUEUED)
+ selected = {request.pk: request for request in queued.filter(created_at__gte=created_after)}
+ for target in DEFAULT_DELETION_TARGETS:
+ horizon = _ttl_horizon(target) if target.copied_from is not None else None
+ if horizon is None:
+ continue
+ candidates = queued.filter(
+ created_at__lt=created_after, request_type=RequestType.EVENT_REMOVAL, end_time__gte=horizon - lookback
+ )
+ for request in candidates:
+ if reaches_target_through_event_uuids(request, target):
+ selected.setdefault(request.pk, request)
+ return list(selected.values())
+
+
# An event removal below this many events is cheap enough that a dedicated ClickHouse Team review buys
# nothing. The sweep job approves it instead, always deferred so the scheduled deletes_job drains it
# alongside everything else rather than running a mutation of its own.
diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.py
index 6ac40dfa44c2..01cef5e16ff3 100644
--- a/posthog/models/deletion_targets.py
+++ b/posthog/models/deletion_targets.py
@@ -115,6 +115,11 @@ class DeletionTarget:
# Read uuids from this table when queueing a deferred deletion. False where the rows duplicate
# another target's uuids, which would queue each one twice.
queue_uuid_candidates: bool = True
+ # The events storage table that holds a copy of each row here, with the same uuid, while ingestion
+ # still writes the event there. None where rows have no such copy. The copy must sit on the same
+ # shard as the row, because the check for rows without a copy reads both tables shard-locally.
+ # A deferred event removal with a HogQL predicate deletes rows here through the uuids of their copies.
+ copied_from: str | None = None
# The event names this table can hold, None meaning unconstrained. Lets a request naming other
# events skip this table without querying it.
stored_events: frozenset[str] | None = None
@@ -209,16 +214,19 @@ EVENTS_JSON = DeletionTarget(
# Flag-evaluation telemetry carries the same person_id and group payload as events, so team and
# queued-uuid sweeps must reach it, and a person sweep matches on person_id like every other
# events-shaped table. Property removal rewrites its event properties and its person properties. A
-# HogQL predicate does not compile against the table, so a request that carries one never sweeps it.
-# Immediate event removal with a predicate leaves the matching rows to the TTL. Deferred event
-# removal and property removal with a predicate refuse while the table holds matching rows.
-# docs/internal/clickhouse-deletion-coverage.md explains these limits.
+# HogQL predicate does not compile against the table, so a request that carries one never runs it
+# there. Immediate event removal with a predicate leaves the matching rows to the TTL. Deferred event
+# removal with a predicate deletes the rows through the uuids of their events copies, and refuses
+# while the table holds a matching row with no copy. Property removal with a predicate refuses while
+# the table holds matching rows. docs/internal/clickhouse-deletion-coverage.md explains these limits.
FLAG_EVALUATIONS = DeletionTarget(
data_table=FLAG_EVALUATIONS_DATA_TABLE,
read_table=FLAG_EVALUATIONS_TABLE,
optional=True,
accepts_property_rewrite=True,
accepts_person_id_rewrite=True,
+ # Both tables shard on sipHash64(distinct_id), so a flag call and its event share a shard.
+ copied_from=EVENTS_DATA_TABLE(),
stored_events=frozenset({FLAG_EVALUATIONS_SOURCE_EVENT}),
ttl_days=FLAG_EVALUATIONS_TTL_DAYS,
)
diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.py
index 6a8c29a57961..5d2d3db4aed5 100644
--- a/posthog/models/test/test_data_deletion_request.py
+++ b/posthog/models/test/test_data_deletion_request.py
@@ -1,6 +1,7 @@
import uuid as uuid_lib
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
+from itertools import pairwise
import pytest
import time_machine
@@ -19,6 +20,7 @@ from posthog.models.data_deletion_request import (
cached_compile_hogql_predicate,
invalidate_compiled_predicate_cache,
)
+from posthog.models.deletion_targets import FLAG_EVALUATIONS
from posthog.models.organization import Organization
from posthog.models.team import Team
@@ -686,6 +688,31 @@ def test_query_backed_deletion_stats_are_rejected():
ddr.fetch_deletion_stats(request)
+@time_machine.travel("2026-06-17T12:00:00Z", tick=False)
[email protected]("start_days_ago,end_days_ago", [(15, 0), (400, 300), (400, 0), (15, -27_000)])
+def test_copy_check_windows_tile_the_request_range(start_days_ago: int, end_days_ago: int) -> None:
+ now = timezone.now()
+ horizon = ddr._ttl_horizon(FLAG_EVALUATIONS)
+ assert horizon is not None
+ request = DataDeletionRequest(
+ team_id=TEAM_ID,
+ start_time=now - timedelta(days=start_days_ago),
+ end_time=now - timedelta(days=end_days_ago),
+ )
+
+ windows = [
+ (params["start_time"], params["end_time"])
+ for _, params in ddr.rows_without_events_copy_criteria(request, FLAG_EVALUATIONS)
+ ]
+
+ assert windows[0][0] == request.start_time
+ assert windows[-1][1] == request.end_time
+ assert all(end == next_start for (_, end), (next_start, _) in pairwise(windows))
+ # Only a window before the TTL horizon or after now may span more than 7 days.
+ assert all(end - start <= timedelta(days=7) for start, end in windows if end > horizon and start < now)
+ assert len(windows) <= 20
+
+
@time_machine.travel("2026-06-17T12:00:00Z", tick=False)
@pytest.mark.parametrize(
"overrides,expected_fragment",