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): report the survivor count instead of blocking on it (#105317)

Paweł Szczur351a9ca9e191
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 039b74135095..2b9da8aa84f2 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -43,7 +43,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, 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.
+- `deletes_job` counts the same way after its own sweep, and reports the result rather than gating on it: it marks the requests verified whether the count came back zero, non-zero, or not at all, and logs an error for the latter two. Proving zero survivors is a full scan, so each count is time-bounded and retried; see the known gap below for why the count cannot complete on `events` today. 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.
@@ -115,6 +115,38 @@ That decision predates this document; the older `posthog/models/async_deletion/d
## Known gaps
+### The survivor count is a report, not a gate
+
+`mark_deletions_verified` marks requests verified whatever the post-sweep count says, and logs an
+error when the count finds survivors or could not be taken at all. Nothing about the count stops a
+run.
+
+No branch of the delete predicate can use an index, because each one keys a dictionary on `team_id`
+and a dictionary lookup is opaque to the primary key. Counting survivors on `events` therefore reads
+the whole table, which exhausts every attempt against the cluster's read-bytes limit rather than its
+time budget, so no larger budget changes the outcome.
+
+Blocking on that stopped every request in the run rather than the ones at risk, and the requests it
+stranded grew the dictionaries the next count had to read, so each week's stall was worse than the
+last. The check is worth blocking on again once it is affordable; narrowing the count to the teams
+named in the dictionaries is the reduction that makes it so.
+
+A non-zero count is not on its own evidence the job skipped work, which is the second reason it does
+not gate.
+
+Every mutation is waited to completion before the count runs, and the person and adhoc arms of the
+predicate only match rows ingested at or before their request's `created_at`. That scope closes when
+the mutation finishes, so a survivor those arms still match would mean ClickHouse did not apply a
+mutation it reported as done.
+
+The team and event arms carry no such bound, deliberately, so a row can arrive after the mutation was
+enqueued and still match one. A count that finds those is reading a straggler the next sweep
+converges on. Failing the run on it would stall the queue on live ingestion.
+
+So a run can mark requests verified without proving the rows are gone. What stops a sweep silently
+removing nothing is upstream of the count: `MutationRunner.reuse_since` keeps a run from adopting a
+mutation an earlier run enqueued, which is the failure the count was added to notice.
+
### `deletes_job` skips `sharded_events_json` by default
`SweepTargetsConfig.skip_targets` defaults to `["sharded_events_json"]`, so the weekly sweep leaves
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 0fc21da8903b..257fe99cb48d 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -90,10 +90,10 @@ class DeleteConfig(dagster.Config):
"raising any failure alert.",
)
verification_max_execution_time: int = pydantic.Field(
- default=1800,
+ default=300,
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.",
+ "Proving none survive is a full scan of the events tables, and the count only reports, so the budget "
+ "buys a cheap answer where one is available rather than a long wait for one that is not.",
)
@property
@@ -1060,26 +1060,35 @@ def mark_deletions_verified(
)
context.add_output_metadata({"unswept_rows": dagster.MetadataValue.json(unswept)})
- # 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, 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.
+ # Reported, never raised, and a non-zero count is not on its own evidence this job skipped work.
+ #
+ # Every mutation is waited to completion before this op runs, and the person and adhoc arms of
+ # the predicate only match rows ingested at or before their request's created_at. That scope
+ # closes when the mutation finishes, so a survivor those arms still match would mean ClickHouse
+ # did not apply a mutation it reported as done.
+ #
+ # The team and event arms carry no such bound, deliberately: a row can arrive after the mutation
+ # was enqueued and still match one. A count that finds those is reading an ordinary straggler
+ # the next sweep converges on, so failing the run on it would stall the queue on live ingestion.
+ #
+ # An unknown count is this check's usual outcome regardless. No branch of the predicate can use
+ # an index, because each keys a dictionary on team_id and a dictionary lookup is opaque to the
+ # primary key, so counting survivors on events reads the whole table and exhausts every attempt
+ # against the cluster's read-bytes limit rather than its time budget. Narrowing the count to the
+ # teams the dictionaries name is what would make it affordable, and worth gating on.
survivors = {table: count for table, count in unswept.items() if count}
+ if survivors:
+ context.log.error(
+ "The sweep finished and rows it should have removed are still readable: "
+ + ", ".join(f"{table}={count}" for table, count in survivors.items())
+ + f". Marking these requests verified anyway. See {COVERAGE_DOC}."
+ )
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 but "
- + "; ".join(problems)
- + f". Leaving these requests pending for the next run. See {COVERAGE_DOC}."
+ if uncounted:
+ context.log.error(
+ "No survivor count attempt completed on: "
+ + ", ".join(uncounted)
+ + f". Marking these requests verified without that check. See {COVERAGE_DOC}."
)
now = timezone.now()
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 89aea3a5a966..265d27a71f86 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -5,7 +5,7 @@ from uuid import UUID
import pytest
import time_machine
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.conf import settings as django_settings
@@ -1234,25 +1234,29 @@ def test_an_unrecognised_skip_target_fails_the_run() -> None:
@pytest.mark.parametrize(
"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},
- ],
+ [{"events": 3}, {"events": None}],
+ ids=["rows_survived", "count_could_not_be_taken"],
)
-def test_marking_is_refused_when_a_count_survives_or_cannot_complete(unswept: dict):
+def test_marking_proceeds_when_the_check_does_not_come_back_clean(unswept: dict):
+ # The count reads the whole events table, so an unknown answer is its ordinary outcome rather
+ # than a signal. Failing the run on either outcome stopped every request instead of the ones at
+ # risk, and the requests it stranded grew the dictionaries the next count had to read.
+ cluster = Mock()
+ cluster.any_host_by_role.return_value.result.return_value = []
+ cluster.any_host.return_value.result.return_value = None
+ dictionary = PendingDeletesDictionary(source=PendingDeletesTable(timestamp=datetime(2026, 9, 1)))
+
with patch("posthog.dags.deletes._count_unswept_rows", return_value=unswept):
- with 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))),
- AdhocEventDeletesDictionary(source=AdhocEventDeletesTable()),
- )
- assert "events" in str(excinfo.value)
+ resources = mark_deletions_verified(
+ build_op_context(),
+ [target.data_table for target in PERSONAL_DATA_TARGETS],
+ DeleteConfig(),
+ cluster,
+ dictionary,
+ AdhocEventDeletesDictionary(source=AdhocEventDeletesTable()),
+ )
+
+ assert resources.pending_deletions_dictionary is dictionary
@pytest.mark.parametrize(