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(deletes): gate marking on unknown counts and guard concurrent runs (#100051)

Paweł Szczurd2db587e0e5d
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 744da202bf57..b5b97b7bec73 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -8,14 +8,14 @@ It is a property of every table that stores rows attributable to a person.
## The sweeps
-| Sweep | Entry point | Predicate columns |
-| ------------------------ | -------------------------------- | ------------------------------------------ |
-| Person deletion (async) | `deletes_job` → `delete_events` | `team_id`, `person_id`, `timestamp` |
-| Team deletion | `deletes_job` → `delete_events` | `team_id` |
-| Queued uuid drain | `deletes_job` → `delete_events` | `team_id`, `uuid` |
-| Person removal request | `delete_person_events_op` | `team_id`, `person_id`, `timestamp` |
-| Event removal request | `execute_event_deletion` | `team_id`, `timestamp`, `event`, + HogQL |
-| Property removal request | `process_property_removal_shard` | `properties`, `person_properties`, + HogQL |
+| Sweep | Entry point | Predicate columns |
+| ------------------------ | -------------------------------- | -------------------------------------------------- |
+| Person deletion (async) | `deletes_job` → `delete_events` | `team_id`, `person_id`, `timestamp`, `inserted_at` |
+| Team deletion | `deletes_job` → `delete_events` | `team_id` |
+| Queued uuid drain | `deletes_job` → `delete_events` | `team_id`, `uuid`, `inserted_at` |
+| Person removal request | `delete_person_events_op` | `team_id`, `person_id`, `timestamp` |
+| Event removal request | `execute_event_deletion` | `team_id`, `timestamp`, `event`, + HogQL |
+| Property removal request | `process_property_removal_shard` | `properties`, `person_properties`, + HogQL |
The first four use only columns every target declares, so they apply unchanged to any registered table.
The last two need more, which is what the capability fields on `DeletionTarget` express.
@@ -39,7 +39,7 @@ Two gates keep that from passing silently.
- `placement_for` refuses a registered target whose storage table is on no data node of any cluster reachable from here while its Distributed proxy still returns rows (`UnreachableTargetError`). Absent from everywhere and empty is still treated as not yet migrated, which is the ordinary pre-rollout state.
- `assert_sweep_complete` runs after the immediate person-removal and event-removal sweeps and counts survivors through the proxy, so rows a mutation never reached fail the request instead of completing it (`UnsweptRowsError`).
-- `deletes_job` counts the same way after its own sweep, but only logs what survived and still marks the requests verified. Its mutations have already run by then, and failing the op would strand the run without undoing anything. Proving zero survivors is a full scan, so the count is time-bounded and reports unknown rather than zero when it runs out.
+- `deletes_job` counts the same way after its own sweep, and refuses to mark the requests verified unless every count completed and came back zero. Proving zero survivors is a full scan, so each count is time-bounded and retried; a count that completes no attempt reports unknown, and unknown blocks the marking the same as a survivor does. The failed run leaves the requests pending, which the next run sweeps again. The delete predicate itself scopes the person and adhoc arms to rows with `inserted_at` no later than the request's own `created_at` (NULL counting as old), and the count shares that predicate, so what gets verified is exactly what got deleted. The bound encodes the deletion contract: a request can only name rows that were already ingested when it was made, and a row cannot be ingested before its event happened, so both `timestamp` and `inserted_at` sit at or before `created_at` for every row a request covers. A row ingested after the request is outside its scope and takes a new request to remove; without the bound, one tenant continuously ingesting backdated events for a pending deletion would block verification for all tenants. `inserted_at` is stamped server-side (`writable_events` does not expose the column), so the bound cannot be forged the way the event `timestamp` can. The team arm stays unbounded: ingestion for a deleted team stops with its token, so late rows there are stragglers the next run converges on.
- A proxy only reads the cluster its engine names, and `sql.py` builds the `events_json` proxy against `CLICKHOUSE_CLUSTER`. So a target stored on another cluster is counted twice: once through the proxy, and once on its storage table through the handle that holds it. Without the second count, a deployment whose storage moved without the proxy following it would report a clean sweep off an empty table.
Both gates probe hosts rather than compare cluster names.
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 43d327a4e6d6..acab993cca43 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -80,10 +80,10 @@ class DeleteConfig(dagster.Config):
"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 "
- "survive is a full scan, so the count is bounded and a count that runs out of time is reported as "
- "unknown rather than as zero.",
+ default=1800,
+ description="Seconds each attempt may spend counting rows the sweep should have removed but did not. "
+ "Proving none survive is a full scan, so each count is bounded; a count that completes no attempt "
+ "blocks the marking instead of passing as clean.",
)
@property
@@ -124,13 +124,25 @@ class MonthlyCleanupConfig(dagster.Config):
)
-# Reads only team_id, person_id, timestamp and uuid, which every registered target declares, so it
-# applies unchanged to all of them. Shared with the post-sweep count so what gets verified is
-# exactly what got deleted.
+# Reads only team_id, person_id, timestamp, uuid and inserted_at, which every registered target
+# declares. Shared with the post-sweep count so what gets verified is exactly what got deleted.
+#
+# The person and adhoc arms bound both timestamp and inserted_at by the request's own created_at:
+# a request can only name rows that were already ingested when it was made, and a row cannot be
+# ingested before its event happened. A row ingested after the request is outside its scope and
+# takes a new request to remove; counting such rows would let a tenant that keeps ingesting
+# backdated events for a pending deletion fail verification for every tenant, and inserted_at is
+# stamped server-side (writable_events does not even expose the column), so the bound cannot be
+# forged the way the event timestamp can. NULL inserted_at predates the column and always counts.
+# The team arm stays unbounded: ingestion for a deleted team stops with its token, so late rows
+# there are pipeline stragglers the next run converges on, not a sustained obligation.
_DELETE_PREDICATE = """or(
- (dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id)) AND timestamp <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))),
+ (dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id))
+ AND timestamp <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))
+ AND (inserted_at IS NULL OR inserted_at <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id)))),
(dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))),
- (dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid)))
+ (dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid))
+ AND (inserted_at IS NULL OR inserted_at <= dictGet(%(adhoc_event_deletes_dictionary)s, 'created_at', (team_id, uuid))))
)"""
@@ -325,7 +337,52 @@ class AdhocEventDeletesDictionary(Dictionary):
)
+# Statuses under which a run's mutations may still land on the cluster: STARTING and STARTED are
+# executing, and a CANCELING run's last mutation keeps applying server-side. QUEUED and
+# NOT_STARTED are left out on purpose. A queued run has done nothing yet, and its own guard will
+# see this run once it starts.
+_EXECUTING_RUN_STATUSES = [
+ dagster.DagsterRunStatus.STARTING,
+ dagster.DagsterRunStatus.STARTED,
+ dagster.DagsterRunStatus.CANCELING,
+]
+
+
[email protected](out=dagster.Out(dagster.Nothing))
+def ensure_no_concurrent_deletes_run(context: dagster.OpExecutionContext) -> None:
+ """Fail this run when another run of the same job, or any squash run, is executing.
+
+ Concurrent deletes runs share their dictionary names, so each run's delete mutations read
+ whichever contents the other run loaded last, and mark_deletions_verified then claims
+ deletions the sweep may not have performed. Any other executing run blocks, deliberately
+ without an election: ranking by creation time lets a run that was queued early and started
+ late outrank a run already past this guard, and two runs then proceed together. Two racing
+ starts can both fail here, which is safe and visible; the run-queue limit named on the job's
+ concurrency tag is what removes that annoyance, not a smarter guard.
+
+ A squash run blocks too. The weekly chain serializes squash before deletes because both
+ issue heavy mutations on the same tables, and manual_deletes_job's preflight can go stale
+ between its check and the sensor launching this run, so the launched run checks again here.
+ This covers direct launchpad starts as well.
+ """
+ blockers: list[str] = []
+ for job_name in (context.job_name, squash_person_overrides.name):
+ records = context.instance.get_run_records(
+ dagster.RunsFilter(job_name=job_name, statuses=_EXECUTING_RUN_STATUSES)
+ )
+ blockers.extend(
+ f"{job_name} run {record.dagster_run.run_id}"
+ for record in records
+ if record.dagster_run.run_id != context.run_id
+ )
+ if blockers:
+ raise dagster.Failure(
+ description="This run yields to: " + "; ".join(blockers) + ". "
+ "Wait for them to finish or cancel them, then start a new run through manual_deletes_job."
+ )
+
+
[email protected](ins={"start_after": dagster.In(dagster.Nothing)})
def get_oldest_person_override_timestamp(
cluster: dagster.ResourceParam[ClickhouseCluster],
) -> datetime:
@@ -730,6 +787,9 @@ def _rows_per_shard(cluster: ClickhouseCluster, query: Query) -> list:
return list(cluster.map_one_host_per_shard(query).result().values())
+_SURVIVOR_COUNT_ATTEMPTS = 3
+
+
def _count_through(
context: dagster.OpExecutionContext,
runner: Callable[[Query], list],
@@ -737,21 +797,27 @@ def _count_through(
params: dict[str, str | int],
max_execution_time: int,
) -> int | None:
- """Survivors on ``table``, or None when the count could not be taken.
+ """Survivors on ``table``, or None when no attempt could complete.
None is deliberately not zero: a count that errored or ran out of time says nothing about
- whether rows remain, and reporting it as clean is the mistake worth avoiding here.
+ whether rows remain, and mark_deletions_verified refuses to mark on it. Each attempt gets the
+ full time budget, and the runner picks a host per call, so a retry also routes around a single
+ slow or sick host.
"""
query = Query(
surviving_rows_sql(table, _DELETE_PREDICATE),
params,
settings={"max_execution_time": str(max_execution_time)},
)
- try:
- return sum(int(rows[0][0]) if rows else 0 for rows in runner(query))
- except Exception as e:
- context.log.warning(f"Could not count what survived the sweep in {table}: {e}")
- return None
+ for attempt in range(1, _SURVIVOR_COUNT_ATTEMPTS + 1):
+ try:
+ return sum(int(rows[0][0]) if rows else 0 for rows in runner(query))
+ except Exception as e:
+ context.log.warning(
+ f"Could not count what survived the sweep in {table} "
+ f"(attempt {attempt}/{_SURVIVOR_COUNT_ATTEMPTS}): {e}"
+ )
+ return None
def _count_unswept_rows(
@@ -818,13 +884,23 @@ def mark_deletions_verified(
# A request marked verified is a claim the rows are gone, and nothing revisits it: the adhoc
# tombstone this op writes also keeps those uuids out of every later run. So a count that came
- # back non-zero has to stop the marking rather than annotate it. Leaving the requests pending
- # costs a repeated sweep next run, which is the recoverable direction.
- remaining = {table: count for table, count in unswept.items() if count}
- if remaining:
+ # back non-zero has to stop the marking rather than annotate it, and a count that could not be
+ # taken has to stop it too, because unknown is not zero. Leaving the requests pending costs a
+ # repeated sweep next run, which is the recoverable direction.
+ survivors = {table: count for table, count in unswept.items() if count}
+ uncounted = sorted(table for table, count in unswept.items() if count is None)
+ if survivors or uncounted:
+ problems = []
+ if survivors:
+ problems.append(
+ "rows the sweep should have removed are still readable: "
+ + ", ".join(f"{table}={count}" for table, count in survivors.items())
+ )
+ if uncounted:
+ problems.append("no survivor count attempt completed on: " + ", ".join(uncounted))
raise dagster.Failure(
- description="The sweep finished and rows it should have removed are still readable: "
- + ", ".join(f"{table}={count}" for table, count in remaining.items())
+ description="The sweep finished but "
+ + "; ".join(problems)
+ f". Leaving these requests pending for the next run. See {COVERAGE_DOC}."
)
@@ -877,11 +953,19 @@ def cleanup_delete_assets(
return True
[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
+ tags={
+ "owner": JobOwners.TEAM_CLICKHOUSE.value,
+ # For a run-queue limit of 1 in Dagster deployment settings, so a second run queues
+ # instead of racing the guard; clickhouse_deletion_sweep_concurrency is the matched
+ # example. ensure_no_concurrent_deletes_run enforces mutual exclusion regardless.
+ "deletes_job_concurrency": "v1",
+ }
+)
def deletes_job():
"""Job that handles deletion of events."""
# Prepare requested deletions data
- oldest_override_timestamp = get_oldest_person_override_timestamp()
+ oldest_override_timestamp = get_oldest_person_override_timestamp(start_after=ensure_no_concurrent_deletes_run())
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())
@@ -910,20 +994,86 @@ def deletes_job():
cleanup_delete_assets(verified_deletion_resources)
+# What every sensor-launched deletes_job run carries. retry_max_attempts is raised because
+# mutation waits can span hours, so a run sees more transient per-host failures than the default
+# allows. manual_deletes_job exists so hand-started runs go through this config too.
+DELETES_RUN_CONFIG = {"resources": {"cluster": {"config": {"retry_max_attempts": 20}}}}
+
+
@dagster.run_status_sensor(
run_status=dagster.DagsterRunStatus.SUCCESS,
monitored_jobs=[squash_person_overrides],
request_job=deletes_job,
)
def run_deletes_after_squash(context):
- # mutation waits can span hours, so allow more transient failures per host before failing the
- # weekly deletes run
return dagster.RunRequest(
run_key=None,
- run_config={"resources": {"cluster": {"config": {"retry_max_attempts": 20}}}},
+ run_config=DELETES_RUN_CONFIG,
)
+# Everything that means a deletes_job or squash run is active or imminent. Unlike the in-job
+# guard, QUEUED and NOT_STARTED count too: the question here is whether launching another run
+# would collide, not which of two started runs came first.
+_ACTIVE_RUN_STATUSES = [
+ dagster.DagsterRunStatus.QUEUED,
+ dagster.DagsterRunStatus.NOT_STARTED,
+ *_EXECUTING_RUN_STATUSES,
+]
+
+
+def ensure_deletes_job_can_start(context: dagster.OpExecutionContext) -> None:
+ """Fail when launching deletes_job now would collide with an active or imminent run.
+
+ A concurrent deletes_job run is the collision the in-job guard exists for; failing here
+ reports it before a run is even launched. A squash run means the weekly chain is already in
+ motion and will launch deletes_job itself on success, so starting one by hand now would race
+ it. Another manual trigger means someone else already asked for a run.
+ """
+ blockers: list[str] = []
+ for job_name in (deletes_job.name, squash_person_overrides.name, context.job_name):
+ records = context.instance.get_run_records(dagster.RunsFilter(job_name=job_name, statuses=_ACTIVE_RUN_STATUSES))
+ blockers.extend(
+ f"{job_name} run {record.dagster_run.run_id}"
+ for record in records
+ if record.dagster_run.run_id != context.run_id
+ )
+ if blockers:
+ raise dagster.Failure(
+ description="deletes_job cannot start while these runs are active: "
+ + "; ".join(blockers)
+ + ". Wait for them to finish, then run manual_deletes_job again."
+ )
+
+
[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
+def manual_deletes_job():
+ """Start a deletes_job run the way the weekly chain does.
+
+ Launch this instead of deletes_job itself. It checks that no deletes_job or squash run is in
+ flight, and its success makes run_deletes_after_manual_trigger request a real deletes_job run
+ with DELETES_RUN_CONFIG. Launching deletes_job directly skips both: the launchpad defaults
+ carry none of that config, and nothing checks the weekly chain before the in-job guard fails
+ the run mid-flight.
+ """
+ ensure_deletes_job_can_start()
+
+
[email protected]_status_sensor(
+ run_status=dagster.DagsterRunStatus.SUCCESS,
+ monitored_jobs=[manual_deletes_job],
+ request_job=deletes_job,
+ # Enabled on registration: a stopped sensor would let manual_deletes_job succeed while
+ # launching nothing, which reads as a started run that never appears.
+ default_status=dagster.DefaultSensorStatus.RUNNING,
+ minimum_interval_seconds=60,
+)
+def run_deletes_after_manual_trigger(context: dagster.RunStatusSensorContext) -> dagster.RunRequest:
+ # The run_key makes each manual_deletes_job success launch at most one deletes_job run.
+ return dagster.RunRequest(run_key=context.dagster_run.run_id, run_config=DELETES_RUN_CONFIG)
+
+
@dagster.op
def find_partitions_to_cleanup(
context: dagster.OpExecutionContext,
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index a8f0614f0d6c..759779218101 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -38,6 +38,7 @@ defs = dagster.Definitions(
create_materialized_column.create_materialized_column,
drop_materialized_column.drop_materialized_column,
deletes.deletes_job,
+ deletes.manual_deletes_job,
export_query_log_archive_to_s3.export_query_log_archive_to_s3,
backfill_materialized_column.backfill_materialized_column,
fix_missing_person_overrides.fix_missing_person_overrides_job,
@@ -69,6 +70,7 @@ defs = dagster.Definitions(
sensors=[
clickhouse_cleanup.run_cleanup_sweep_after_deletes,
deletes.run_deletes_after_squash,
+ deletes.run_deletes_after_manual_trigger,
data_deletion_requests.data_deletion_request_pickup_sensor,
data_deletion_requests.verify_queued_deletion_requests,
],
diff --git a/posthog/dags/tests/conftest.py b/posthog/dags/tests/conftest.py
index 107a70c1ecbe..5acbe732bb67 100644
--- a/posthog/dags/tests/conftest.py
+++ b/posthog/dags/tests/conftest.py
@@ -5,8 +5,6 @@ __all__ = ["django_db_setup"]
from collections.abc import Iterator
from contextlib import contextmanager
-from datetime import datetime
-from uuid import UUID
import pytest
from posthog.test.base import reset_clickhouse_database, reset_clickhouse_database_if_dirty
@@ -29,12 +27,18 @@ from posthog.dags.tests.dagster_pg_fixtures import ( # noqa: F401
from posthog.persons_db import persons_db_connection
-def insert_flag_evaluations(rows: list[tuple[int, str, str | UUID, str | UUID, datetime]], client: Client) -> None:
- """Insert rows of (team_id, distinct_id, person_id, uuid, timestamp) into flag_evaluations."""
- client.execute(
- "INSERT INTO writable_flag_evaluations (team_id, distinct_id, person_id, uuid, timestamp) VALUES",
- rows,
- )
+def insert_flag_evaluations(rows: list[tuple], client: Client) -> None:
+ """Insert rows of (team_id, distinct_id, person_id, uuid, timestamp[, inserted_at]) into flag_evaluations.
+
+ Six-element rows pin inserted_at, for tests whose deletion requests carry a created_at in the
+ past: the sweep predicate only covers rows ingested before their request was created, and the
+ column's DEFAULT stamps insert time, which would put the row out of every backdated request's
+ scope.
+ """
+ columns = "team_id, distinct_id, person_id, uuid, timestamp"
+ if rows and len(rows[0]) == 6:
+ columns += ", inserted_at"
+ client.execute(f"INSERT INTO writable_flag_evaluations ({columns}) VALUES", rows)
def refresh_person_from_persons_db(person) -> None:
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 4e7277a0ea6a..8be9f8841b9e 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -9,13 +9,16 @@ from unittest.mock import patch
from django.conf import settings as django_settings
+import dagster
from clickhouse_driver import Client
from dagster import build_op_context
-from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner
+from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner, NodeRole, Query
from posthog.dags.common.staged_dictionary import create_on_every_cluster
from posthog.dags.deletes import (
_DELETE_PREDICATE,
+ _SURVIVOR_COUNT_ATTEMPTS,
+ DELETES_RUN_CONFIG,
AdhocEventDeletesDictionary,
AdhocEventDeletesTable,
DeleteConfig,
@@ -23,13 +26,19 @@ from posthog.dags.deletes import (
PendingDeletesDictionary,
PendingDeletesTable,
StagedDictionary,
+ _count_through,
_count_unswept_rows,
_delete_predicate_params,
cleanup_old_events_by_partition,
deletes_job,
+ ensure_no_concurrent_deletes_run,
find_partitions_to_cleanup,
+ manual_deletes_job,
+ mark_deletions_verified,
monthly_old_events_cleanup_job,
+ run_deletes_after_manual_trigger,
)
+from posthog.dags.person_overrides import squash_person_overrides
from posthog.dags.tests.conftest import insert_flag_evaluations
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.deletion_targets import EVENTS, TargetPlacement
@@ -58,14 +67,18 @@ def test_full_job_person_deletes(cluster: ClickhouseCluster):
events = [(i, f"distinct_id_{i}", UUID(int=i), timestamp - timedelta(hours=i)) for i in range(event_count)]
def insert_events(client: Client) -> None:
+ # Straight into the storage table with inserted_at pinned to the event time:
+ # writable_events does not expose inserted_at, and each deletion request below carries
+ # created_at an hour after its event, so the DEFAULT of insert time would put every row
+ # out of its backdated request's scope.
client.execute(
- """INSERT INTO writable_events (team_id, distinct_id, person_id, timestamp)
+ f"""INSERT INTO {EVENTS_DATA_TABLE()} (team_id, distinct_id, person_id, timestamp, inserted_at)
VALUES
""",
- events,
+ [(*event, event[3]) for event in events],
)
- cluster.any_host(insert_events).result()
+ cluster.any_host_by_role(insert_events, NodeRole.DATA).result()
# Flag-evaluation rows for one person whose deletion lands inside the window and one whose
# deletion sits past the override watermark, mirroring the two event assertions below. The
@@ -75,7 +88,14 @@ def test_full_job_person_deletes(cluster: ClickhouseCluster):
partial(
insert_flag_evaluations,
[
- (i, f"distinct_id_{i}", UUID(int=i), UUID(int=i), timestamp - timedelta(hours=i))
+ (
+ i,
+ f"distinct_id_{i}",
+ UUID(int=i),
+ UUID(int=i),
+ timestamp - timedelta(hours=i),
+ timestamp - timedelta(hours=i),
+ )
for i in (swept_person, retained_person)
],
)
@@ -396,12 +416,14 @@ def test_full_job_adhoc_event_deletes(cluster: ClickhouseCluster):
return {}
return {(row[0], row[1]): row[2] for row in result}
- # Insert some pending deletions
+ # Insert some pending deletions. created_at is explicit and past every ingestion above:
+ # the sweep only covers rows ingested before their request was created, and the column's
+ # DEFAULT would race the data inserts across host clocks at sub-second distance.
def insert_adhoc_event_deletes(client: Client) -> None:
- deletes = [(events[i][0], events[i][2]) for i in range(delete_count)]
+ deletes = [(events[i][0], events[i][2], timestamp) for i in range(delete_count)]
client.execute(
- """INSERT INTO adhoc_events_deletion (team_id, uuid)
+ """INSERT INTO adhoc_events_deletion (team_id, uuid, created_at)
VALUES
""",
deletes,
@@ -420,11 +442,12 @@ def test_full_job_adhoc_event_deletes(cluster: ClickhouseCluster):
return result[0][0]
cluster.any_host(insert_events).result()
- cluster.any_host(insert_adhoc_event_deletes).result()
# The queue holds (team_id, uuid) and the drain applies it to every personal-data table, so a
# flag-evaluation row sharing a queued uuid has to go with the event. This is the assumption
# the producer must honor: mirror the source event's uuid, or the two tables diverge here.
+ # Inserted before the deletion requests: the sweep only covers rows ingested before their
+ # request was created, which is the order production follows too.
queued_uuid, unqueued_uuid = 5, delete_count + 5
cluster.any_host(
partial(
@@ -433,6 +456,8 @@ def test_full_job_adhoc_event_deletes(cluster: ClickhouseCluster):
)
).result()
+ cluster.any_host(insert_adhoc_event_deletes).result()
+
# Check preconditions
initial_events = cluster.any_host(partial(get_by_team_and_uuid, "writable_events")).result()
assert len(initial_events) == event_count # All events present initially
@@ -891,11 +916,39 @@ def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: Clickh
)
def insert_events(client: Client) -> None:
+ # Straight into the storage table: writable_events does not expose inserted_at. Distinct
+ # uuids keep separate ORDER BY keys, and one NULL inserted_at covers rows that predate
+ # the column, which must still count.
client.execute(
- "INSERT INTO writable_events (team_id, distinct_id, person_id, timestamp) VALUES",
- [(team_id, "d", person_uuid, timestamp - timedelta(hours=1))],
+ f"INSERT INTO {EVENTS_DATA_TABLE()} (uuid, team_id, distinct_id, person_id, timestamp, inserted_at) VALUES",
+ [
+ (UUID(int=1001), team_id, "d", person_uuid, timestamp - timedelta(hours=1), timestamp),
+ (UUID(int=1002), team_id, "d", person_uuid, timestamp - timedelta(hours=2), None),
+ ],
)
+ def insert_late_event(client: Client) -> None:
+ client.execute(
+ f"INSERT INTO {EVENTS_DATA_TABLE()} (uuid, team_id, distinct_id, person_id, timestamp, inserted_at) VALUES",
+ [
+ (
+ UUID(int=1003),
+ team_id,
+ "d",
+ person_uuid,
+ timestamp - timedelta(hours=1),
+ timestamp + timedelta(hours=2),
+ )
+ ],
+ )
+
+ def count_late_event_rows(client: Client) -> int:
+ [[count]] = client.execute(
+ "SELECT count() FROM events WHERE uuid = %(uuid)s AND _row_exists = 1",
+ {"uuid": UUID(int=1003)},
+ )
+ return count
+
try:
cluster.any_host(table.create).result()
cluster.any_host(insert_person_deletion).result()
@@ -903,14 +956,14 @@ def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: Clickh
cluster.any_host(dictionary.load).result()
cluster.any_host(create_adhoc).result()
cluster.any_host(adhoc.load).result()
- cluster.any_host(insert_events).result()
+ cluster.any_host_by_role(insert_events, NodeRole.DATA).result()
context = build_op_context()
before = _count_unswept_rows(
context, cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time
)
surviving = before["events"]
- assert surviving is not None and surviving >= 1, "the count cannot see rows the sweep has not removed yet"
+ assert surviving is not None and surviving >= 2, "the count cannot see rows the sweep has not removed yet"
runner = LightweightDeleteMutationRunner(
table=EVENTS_DATA_TABLE(),
@@ -922,6 +975,16 @@ def test_the_post_sweep_count_reports_rows_the_sweep_left_behind(cluster: Clickh
after = _count_unswept_rows(context, cluster, 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)
+ 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"
+ )
finally:
cluster.any_host(dictionary.drop).result()
cluster.any_host(adhoc.drop).result()
@@ -960,9 +1023,10 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(cluste
)
def insert_events(client: Client) -> None:
+ # Straight into the storage table: writable_events does not expose inserted_at.
client.execute(
- "INSERT INTO writable_events (team_id, distinct_id, person_id, timestamp) VALUES",
- [(team_id, "d", person_uuid, timestamp - timedelta(hours=1))],
+ f"INSERT INTO {EVENTS_DATA_TABLE()} (uuid, team_id, distinct_id, person_id, timestamp, inserted_at) VALUES",
+ [(UUID(int=1004), team_id, "d", person_uuid, timestamp - timedelta(hours=1), timestamp)],
)
# A second handle over the same node stands in for a target whose storage is elsewhere.
@@ -976,11 +1040,15 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(cluste
cluster.any_host(dictionary.load).result()
cluster.any_host(partial(adhoc.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()
cluster.any_host(adhoc.load).result()
- cluster.any_host(insert_events).result()
+ cluster.any_host_by_role(insert_events, NodeRole.DATA).result()
with patch("posthog.dags.deletes.resolve_placements", return_value=[placement]):
counts = _count_unswept_rows(
- build_op_context(), cluster, dictionary, adhoc, DeleteConfig().verification_max_execution_time
+ build_op_context(),
+ cluster,
+ dictionary,
+ adhoc,
+ DeleteConfig().verification_max_execution_time,
)
storage = counts[EVENTS.data_table]
@@ -989,3 +1057,111 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(cluste
cluster.any_host(dictionary.drop).result()
cluster.any_host(adhoc.drop).result()
cluster.any_host(table.drop).result()
+
+
+ "unswept",
+ [
+ {"events": 3},
+ # None is a count that completed no attempt. Marking on it is the mistake this gate
+ # exists to stop: unknown is not zero.
+ {"events": None},
+ ],
+)
+def test_marking_is_refused_when_a_count_survives_or_cannot_complete(unswept: dict):
+ with patch("posthog.dags.deletes._count_unswept_rows", return_value=unswept):
+ with pytest.raises(dagster.Failure) as excinfo:
+ mark_deletions_verified(
+ build_op_context(),
+ DeleteConfig(),
+ cast(ClickhouseCluster, None),
+ PendingDeletesDictionary(source=PendingDeletesTable(timestamp=datetime(2026, 9, 1))),
+ AdhocEventDeletesDictionary(source=AdhocEventDeletesTable()),
+ )
+ assert "events" in str(excinfo.value)
+
+
+ "failing_attempts,expected",
+ [
+ (1, 5),
+ (_SURVIVOR_COUNT_ATTEMPTS, None),
+ ],
+)
+def test_the_survivor_count_retries_before_reporting_unknown(failing_attempts: int, expected: int | None):
+ calls = {"count": 0}
+
+ def runner(query: Query) -> list:
+ calls["count"] += 1
+ if calls["count"] <= failing_attempts:
+ raise TimeoutError("count exceeded max_execution_time")
+ return [[[5]]]
+
+ assert _count_through(build_op_context(), runner, "events", {}, 300) == expected
+
+
+ "blocking_job",
+ [
+ deletes_job,
+ # A squash run blocks whatever its age: manual_deletes_job's preflight can go stale
+ # before the sensor launches the run, so the guard checks squash again at run start.
+ squash_person_overrides,
+ ],
+)
+def test_the_deletes_guard_yields_to_an_executing_deletes_or_squash_run(blocking_job: dagster.JobDefinition):
+ assert "ensure_no_concurrent_deletes_run" in deletes_job.graph.node_names()
+
+ @dagster.job(name=deletes_job.name)
+ def guard_only_job() -> None:
+ ensure_no_concurrent_deletes_run()
+
+ instance = dagster.DagsterInstance.ephemeral()
+ assert guard_only_job.execute_in_process(instance=instance).success, "a lone run must pass its own guard"
+
+ instance.create_run_for_job(job_def=blocking_job, status=dagster.DagsterRunStatus.STARTED)
+ result = guard_only_job.execute_in_process(instance=instance, raise_on_error=False)
+ assert not result.success
+
+
+ "blocking_job,status",
+ [
+ (deletes_job, dagster.DagsterRunStatus.STARTED),
+ # A run that has not started yet blocks here even though the in-job guard ignores it: it
+ # is a collision about to happen, and the manual trigger has launched nothing yet.
+ (squash_person_overrides, dagster.DagsterRunStatus.NOT_STARTED),
+ ],
+)
+def test_the_manual_trigger_refuses_while_the_weekly_chain_is_active(
+ blocking_job: dagster.JobDefinition, status: dagster.DagsterRunStatus
+):
+ instance = dagster.DagsterInstance.ephemeral()
+ assert manual_deletes_job.execute_in_process(instance=instance).success
+
+ instance.create_run_for_job(job_def=blocking_job, status=status)
+ result = manual_deletes_job.execute_in_process(instance=instance, raise_on_error=False)
+ assert not result.success
+
+
+def test_the_manual_trigger_sensor_launches_a_real_deletes_run():
+ # A stopped sensor would let manual_deletes_job succeed while launching nothing, and a lost
+ # run config would hand manual runs the default retry budget the weekly runs outgrew.
+ sensor = run_deletes_after_manual_trigger
+ assert sensor.default_status == dagster.DefaultSensorStatus.RUNNING
+
+ manual_run = dagster.DagsterRun(job_name="manual_deletes_job", run_id="22222222-2222-2222-2222-222222222222")
+ request = sensor(
+ dagster.build_run_status_sensor_context(
+ sensor_name="run_deletes_after_manual_trigger",
+ dagster_event=dagster.DagsterEvent(
+ event_type_value=dagster.DagsterEventType.RUN_SUCCESS.value, job_name="manual_deletes_job"
+ ),
+ dagster_instance=dagster.DagsterInstance.ephemeral(),
+ dagster_run=manual_run,
+ )
+ )
+ assert isinstance(request, dagster.RunRequest)
+ assert request.run_config == DELETES_RUN_CONFIG
+ # One deletes_job per manual success: re-evaluating the same event must not launch another.
+ assert request.run_key == "22222222-2222-2222-2222-222222222222"