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(persons): drain only up to the version the sweep removed (#111396)

Eli Reisman000ac49165c9
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.py
index 606fc1ad7df0..d569f449a67b 100644
--- a/posthog/dags/clickhouse_cleanup.py
+++ b/posthog/dags/clickhouse_cleanup.py
@@ -1273,10 +1273,17 @@ PG_QUEUE_RETRY_BACKOFF_SECONDS = 1.0
PERSIST_RETRY_POLICY = dagster.RetryPolicy(max_retries=3, delay=60, backoff=dagster.Backoff.EXPONENTIAL)
+@frozen
+class _QueuedPerson:
+ team_id: int
+ person_id: str
+ max_version: int
+
+
def _write_queue_page(
connection: psycopg2.extensions.connection,
cursor: psycopg2.extensions.cursor,
- page: list[tuple[int, str]],
+ page: list[_QueuedPerson],
deleted_at: datetime | None,
) -> int:
"""Upsert one page, retrying a lock or deadlock conflict. Returns the retries it took."""
@@ -1284,16 +1291,23 @@ def _write_queue_page(
deadline = time.monotonic() + PG_QUEUE_RETRY_WINDOW_SECONDS
while True:
try:
+ # deleted_at and max_version only move forward. A run re-executed from a later op gets a new
+ # deleted_at but keeps its old snapshot, so its bound must never replace a newer run's higher one.
execute_values(
cursor,
f"""
- INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at)
+ INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at, max_version)
VALUES %s
ON CONFLICT (team_id, person_uuid) DO UPDATE
- SET deleted_at = EXCLUDED.deleted_at, blocked_at = NULL
- WHERE {PG_CLEANUP_QUEUE_TABLE}.deleted_at IS DISTINCT FROM EXCLUDED.deleted_at
+ SET deleted_at = EXCLUDED.deleted_at,
+ max_version = GREATEST({PG_CLEANUP_QUEUE_TABLE}.max_version, EXCLUDED.max_version),
+ blocked_at = NULL
+ WHERE {PG_CLEANUP_QUEUE_TABLE}.deleted_at < EXCLUDED.deleted_at
+ OR ({PG_CLEANUP_QUEUE_TABLE}.deleted_at = EXCLUDED.deleted_at
+ AND ({PG_CLEANUP_QUEUE_TABLE}.max_version IS NULL
+ OR {PG_CLEANUP_QUEUE_TABLE}.max_version < EXCLUDED.max_version))
""",
- [(team_id, str(person_id), deleted_at) for team_id, person_id in page],
+ [(person.team_id, person.person_id, deleted_at, person.max_version) for person in page],
page_size=1000,
)
return retries
@@ -1341,18 +1355,21 @@ def persist_deleted_persons(
# keeps a dry run from dialing Postgres at all.
persons_database = psycopg2.connect(persons_database_url, connect_timeout=10)
- def read_page(client: Client, after: tuple[int, str] | None) -> list[tuple[int, str]]:
+ def read_page(client: Client, after: tuple[int, str] | None) -> list[_QueuedPerson]:
# Reads the snapshot directly rather than the dictionary's query, so adding attributes to
# the dictionary cannot silently change the shape of what gets queued. Keyset pagination
- # over (team_id, person_id) follows the table's sort key, and DISTINCT collapses the
+ # over (team_id, person_id) follows the table's sort key, and GROUP BY collapses the
# duplicate versions a retried snapshot insert can leave in the ReplacingMergeTree.
+ # max(max_version) is the bound the dictionary hands delete_persons, so the drain deletes
+ # in Postgres only the versions this run deletes in ClickHouse.
page_filter = "AND (team_id, person_id) > (%(after_team)s, toUUID(%(after_person)s))" if after else ""
- return client.execute(
+ rows = client.execute(
f"""
- SELECT DISTINCT team_id, person_id FROM {run.persons.qualified_name}
+ SELECT team_id, person_id, max(max_version) FROM {run.persons.qualified_name}
WHERE run_id = %(run_id)s
AND (team_id, person_id) NOT IN ({run.revived.run_keys_query})
{page_filter}
+ GROUP BY team_id, person_id
ORDER BY team_id, person_id
LIMIT %(limit)s
""",
@@ -1364,6 +1381,10 @@ def persist_deleted_persons(
},
settings=run.query_settings,
)
+ return [
+ _QueuedPerson(team_id=team_id, person_id=str(person_id), max_version=max_version)
+ for team_id, person_id, max_version in rows
+ ]
deleted_at = run.distinct_ids_deleted_at
written = 0
@@ -1389,7 +1410,8 @@ def persist_deleted_persons(
# The WHERE keeps a retried op from rewriting rows that already hold this run's
# deleted_at: an unconditional DO UPDATE writes a new tuple version per row, so a retry
# over millions of rows would leave that many dead tuples for the persons writer to
- # vacuum.
+ # vacuum. The max_version clause lets a retry of this run fill in a row an older build
+ # queued without one.
conflict_retries += _write_queue_page(persons_database, cursor, page, deleted_at)
# The conflict guard makes rowcount "rows changed", not "rows queued"; the metric is
# the queued set, which is the page.
@@ -1399,8 +1421,8 @@ def persist_deleted_persons(
persons_database.commit()
if len(page) < PERSIST_PAGE_SIZE:
break
- last_team, last_person = page[-1]
- after = (last_team, str(last_person))
+ last = page[-1]
+ after = (last.team_id, last.person_id)
finally:
persons_database.close()
diff --git a/posthog/dags/person_pg_cleanup_drain.py b/posthog/dags/person_pg_cleanup_drain.py
index 2065956d916f..ec4e583be30f 100644
--- a/posthog/dags/person_pg_cleanup_drain.py
+++ b/posthog/dags/person_pg_cleanup_drain.py
@@ -8,6 +8,8 @@ delete them.
The queue is advisory. A person can be revived in Postgres after it was queued, so the job never
deletes on the queue's word: it hands each batch to personhog's DeleteTombstonedPersons, which
deletes a person only while it is still tombstoned, under row locks, and reports the rest back.
+It also deletes only at or below max_version, the highest ClickHouse version the sweep removed, so a
+person tombstoned again after that sweep stays. A row without max_version is never deleted.
Every call does a bounded amount of work: persons that fit the call's row budget are deleted
whole, and a person with more dependent rows than that gives up a bounded slice per call and
comes back as pending until it fits. The job sends pending persons again until none come back, so
@@ -56,7 +58,11 @@ from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, describe_runs
from posthog.dataclasses import frozen
from posthog.metrics import pushed_metrics_registry
from posthog.personhog_client.client import PersonHogClient, personhog_call, require_personhog_client
-from posthog.personhog_client.proto import DeleteTombstonedPersonsRequest, DeleteTombstonedPersonsResponse
+from posthog.personhog_client.proto import (
+ DeleteTombstonedPersonsRequest,
+ DeleteTombstonedPersonsResponse,
+ VersionBoundedPerson,
+)
logger = dagster.get_dagster_logger(__name__)
@@ -65,7 +71,7 @@ PG_APPLICATION_NAME = "person_pg_cleanup_drain"
# Pushing replaces every gauge stored under this name, so one push carries the whole set.
DRAIN_METRICS_JOB = "person_pg_cleanup_drain"
-# Server-side cap on DeleteTombstonedPersonsRequest.person_uuids.
+# Server-side cap on DeleteTombstonedPersonsRequest.bounded_persons.
RPC_MAX_UUIDS = 1000
# The sweep polls for the drain this often, so checking for the sweep more often only loads
@@ -218,6 +224,7 @@ class QueueRow:
team_id: int
person_uuid: str
deleted_at: datetime
+ max_version: int | None
@frozen
@@ -233,6 +240,7 @@ class Chunk:
team_id: int
deleted_at: datetime
person_uuids: tuple[str, ...]
+ max_versions: Mapping[str, int]
@frozen(frozen=False)
@@ -246,10 +254,12 @@ class DrainTotals:
requests_pending_resent: int = 0
persons_deleted: int = 0
persons_skipped_live: int = 0
+ persons_skipped_version: int = 0
persons_not_found: int = 0
persons_blocked: int = 0
rows_deleted: int = 0
rows_stamped_blocked: int = 0
+ rows_unversioned: int = 0
blocked_sample: list[str] = field(default_factory=list)
queue_rows_deleted: int = 0
step_rows_min: int = 0
@@ -277,10 +287,12 @@ class DrainTotals:
"requests_pending_resent": dagster.MetadataValue.int(self.requests_pending_resent),
"persons_deleted": dagster.MetadataValue.int(self.persons_deleted),
"persons_skipped_live": dagster.MetadataValue.int(self.persons_skipped_live),
+ "persons_skipped_version": dagster.MetadataValue.int(self.persons_skipped_version),
"persons_not_found": dagster.MetadataValue.int(self.persons_not_found),
"persons_blocked": dagster.MetadataValue.int(self.persons_blocked),
"rows_deleted": dagster.MetadataValue.int(self.rows_deleted),
"rows_stamped_blocked": dagster.MetadataValue.int(self.rows_stamped_blocked),
+ "rows_unversioned": dagster.MetadataValue.int(self.rows_unversioned),
"blocked_sample": dagster.MetadataValue.text(", ".join(self.blocked_sample) or "none"),
"queue_rows_deleted": dagster.MetadataValue.int(self.queue_rows_deleted),
"step_rows_min": dagster.MetadataValue.int(self.step_rows_min),
@@ -306,15 +318,26 @@ def chunks_for_page(rows: Sequence[QueueRow], rpc_batch_size: int) -> list[Chunk
Grouping by deleted_at as well as team_id is what lets the queue delete carry a deleted_at
guard, so a row the sweep re-queued between the read and the delete is left for the next run.
+ A row without max_version goes in no request.
"""
- grouped: dict[tuple[int, datetime], list[str]] = defaultdict(list)
+ grouped: dict[tuple[int, datetime], dict[str, int]] = defaultdict(dict)
for row in rows:
- grouped[(row.team_id, row.deleted_at)].append(row.person_uuid)
- return [
- Chunk(team_id=team_id, deleted_at=deleted_at, person_uuids=tuple(uuids[start : start + rpc_batch_size]))
- for (team_id, deleted_at), uuids in grouped.items()
- for start in range(0, len(uuids), rpc_batch_size)
- ]
+ if row.max_version is not None:
+ grouped[(row.team_id, row.deleted_at)][row.person_uuid] = row.max_version
+ chunks: list[Chunk] = []
+ for (team_id, deleted_at), max_versions in grouped.items():
+ uuids = list(max_versions)
+ for start in range(0, len(uuids), rpc_batch_size):
+ batch = tuple(uuids[start : start + rpc_batch_size])
+ chunks.append(
+ Chunk(
+ team_id=team_id,
+ deleted_at=deleted_at,
+ person_uuids=batch,
+ max_versions={uuid: max_versions[uuid] for uuid in batch},
+ )
+ )
+ return chunks
PgRecovery = Literal["retry", "reconnect"]
@@ -399,7 +422,7 @@ def _read_page(
cursor_filter = "AND (team_id, person_uuid) > (%(after_team)s, %(after_uuid)s::uuid)" if after else ""
cursor.execute(
f"""
- SELECT team_id, person_uuid, deleted_at
+ SELECT team_id, person_uuid, deleted_at, max_version
FROM {PG_CLEANUP_QUEUE_TABLE}
WHERE (blocked_at IS NULL OR blocked_at < %(blocked_before)s)
{cursor_filter}
@@ -414,8 +437,8 @@ def _read_page(
},
)
return [
- QueueRow(team_id=team_id, person_uuid=str(person_uuid), deleted_at=deleted_at)
- for team_id, person_uuid, deleted_at in cursor.fetchall()
+ QueueRow(team_id=team_id, person_uuid=str(person_uuid), deleted_at=deleted_at, max_version=max_version)
+ for team_id, person_uuid, deleted_at, max_version in cursor.fetchall()
]
@@ -630,7 +653,12 @@ class _Drain:
"""
assert self.client is not None
client = self.client
- request = DeleteTombstonedPersonsRequest(team_id=chunk.team_id, person_uuids=list(uuids))
+ request = DeleteTombstonedPersonsRequest(
+ team_id=chunk.team_id,
+ bounded_persons=[
+ VersionBoundedPerson(person_uuid=uuid, max_version=chunk.max_versions[uuid]) for uuid in uuids
+ ],
+ )
spent = 0.0
failures = 0
while True:
@@ -693,6 +721,14 @@ class _Drain:
self.totals.rpc_seconds_total += elapsed
self.totals.rpc_seconds_max = max(self.totals.rpc_seconds_max, elapsed)
self.totals.rpc_seconds_last = elapsed
+ if not response.version_guard_applied:
+ # A replica that predates bounded_persons reads an empty person_uuids and answers
+ # with nothing deleted. Applying that answer would drop every queue row as not found.
+ raise dagster.Failure(
+ "personhog did not apply the version bounds; deploy personhog-replica with bounded_persons "
+ "support before running the drain",
+ metadata={**self.totals.as_metadata(), **_request_metadata(chunk, uuids)},
+ )
self.grow_step()
return response
@@ -729,10 +765,15 @@ class _Drain:
unresolved = set(blocked) | set(response.pending_person_uuids)
resolved = [uuid for uuid in sent if uuid not in unresolved]
# Skipped-live rows go too: the queue row is stale, and the sweep queues the person again
- # if it is ever tombstoned again.
+ # if it is ever tombstoned again. So do rows skipped above their version bound: the newer
+ # tombstone has its own ClickHouse rows, and the sweep that removes them queues the person
+ # again with a higher bound.
self.totals.persons_deleted += response.deleted_count
self.totals.persons_skipped_live += response.skipped_live_count
- self.totals.persons_not_found += len(resolved) - response.deleted_count - response.skipped_live_count
+ self.totals.persons_skipped_version += response.skipped_version_count
+ self.totals.persons_not_found += (
+ len(resolved) - response.deleted_count - response.skipped_live_count - response.skipped_version_count
+ )
self.totals.persons_blocked += len(blocked)
self.totals.rows_deleted += response.rows_deleted
self.totals.queue_rows_deleted += self.timed_pg(lambda cursor: _delete_queue_rows(cursor, chunk, resolved))
@@ -758,6 +799,7 @@ class _Drain:
for outcome, delta in (
("deleted", after.persons_deleted - before.persons_deleted),
("skipped_live", after.persons_skipped_live - before.persons_skipped_live),
+ ("skipped_version", after.persons_skipped_version - before.persons_skipped_version),
("not_found", after.persons_not_found - before.persons_not_found),
("blocked", after.persons_blocked - before.persons_blocked),
):
@@ -787,6 +829,7 @@ class _Drain:
return DrainTotals(
persons_deleted=self.totals.persons_deleted,
persons_skipped_live=self.totals.persons_skipped_live,
+ persons_skipped_version=self.totals.persons_skipped_version,
persons_not_found=self.totals.persons_not_found,
persons_blocked=self.totals.persons_blocked,
rows_deleted=self.totals.rows_deleted,
@@ -803,6 +846,7 @@ class _Drain:
emitted = self.snapshot()
try:
for page in self.pages():
+ self.totals.rows_unversioned += sum(row.max_version is None for row in page)
if self.config.dry_run:
continue
for chunk in chunks_for_page(page, self.config.rpc_batch_size):
@@ -829,12 +873,15 @@ class _Drain:
def log_progress(self) -> None:
totals = self.totals
self.context.log.info(
- "%d pages, %d rows: deleted=%d skipped_live=%d not_found=%d blocked=%d rows_deleted=%d, "
- "%d pending re-sends, step %d rows (%d..%d), rpc mean %.3fs, %d rpc errors, %d pg reconnects",
+ "%d pages, %d rows (%d unversioned): deleted=%d skipped_live=%d skipped_version=%d not_found=%d "
+ "blocked=%d rows_deleted=%d, %d pending re-sends, step %d rows (%d..%d), rpc mean %.3fs, %d rpc errors, "
+ "%d pg reconnects",
totals.pages,
totals.rows_read,
+ totals.rows_unversioned,
totals.persons_deleted,
totals.persons_skipped_live,
+ totals.persons_skipped_version,
totals.persons_not_found,
totals.persons_blocked,
totals.rows_deleted,
@@ -902,6 +949,16 @@ def _drain_gauges(totals: DrainTotals, completed_at: float) -> list[PublishedGau
help_text="Queued persons that are live in Postgres, so the drain left them alone",
value=totals.persons_skipped_live,
),
+ PublishedGauge(
+ name=f"{prefix}persons_skipped_version",
+ help_text="Queued persons tombstoned again above their version bound, so the drain left them alone",
+ value=totals.persons_skipped_version,
+ ),
+ PublishedGauge(
+ name=f"{prefix}rows_unversioned",
+ help_text="Queue rows without a version bound, which the drain leaves queued",
+ value=totals.rows_unversioned,
+ ),
PublishedGauge(
name=f"{prefix}persons_not_found",
help_text="Queued persons with no Postgres row, so the queue row was already stale",
diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.py
index e1e960d66a7c..502d2f9bc64f 100644
--- a/posthog/dags/tests/test_clickhouse_cleanup.py
+++ b/posthog/dags/tests/test_clickhouse_cleanup.py
@@ -190,7 +190,9 @@ def seed_decoy_run(cluster: ClickhouseCluster, spared_person: str, spared_distin
def queued_rows(conn) -> list[tuple]:
with conn.cursor() as cursor:
- cursor.execute(f"SELECT team_id, person_uuid, deleted_at, blocked_at FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 2")
+ cursor.execute(
+ f"SELECT team_id, person_uuid, deleted_at, blocked_at, max_version FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 2"
+ )
return cursor.fetchall()
@@ -354,7 +356,8 @@ def test_the_age_floor_rejects_a_negative_age():
@pytest.mark.django_db
def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, persons_database):
- deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ deleted = create_person(team_id=TEAM_ID, version=0)
+ create_person(uuid=deleted, team_id=TEAM_ID, version=3, is_deleted=True)
create_person(team_id=TEAM_ID, version=0)
result = run_job(cluster, persons_database)
@@ -362,10 +365,12 @@ def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, per
assert result.output_for_node("publish_sweep_metrics").queued_for_postgres == 1
rows = queued_rows(persons_database)
assert len(rows) == 1
- team_id, person_uuid, deleted_at, blocked_at = rows[0]
+ team_id, person_uuid, deleted_at, blocked_at, max_version = rows[0]
assert (team_id, str(person_uuid)) == (TEAM_ID, deleted)
assert deleted_at is not None
assert blocked_at is None
+ # The highest version the run deleted from ClickHouse, which bounds the Postgres delete.
+ assert max_version == 3
# A second run must not raise on the primary key: it re-queues persons the drain has not
# reached yet.
@@ -430,7 +435,7 @@ def test_resweeping_a_pending_person_refreshes_deleted_at_and_clears_blocked_at(
# the row blocked forever and leak that person's Postgres rows for good.
deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
run_job(cluster, persons_database)
- [(_, _, first_deleted_at, _)] = queued_rows(persons_database)
+ [(_, _, first_deleted_at, _, _)] = queued_rows(persons_database)
# Stand in for the drain having found the person blocked.
with persons_database.cursor() as cursor:
@@ -446,6 +451,7 @@ def test_resweeping_a_pending_person_refreshes_deleted_at_and_clears_blocked_at(
assert len(rows) == 1, "the row is keyed on (team_id, person_uuid), so this stays a single row"
assert rows[0][2] > first_deleted_at, "deleted_at must move to the later sweep"
assert rows[0][3] is None, "blocked_at must be cleared so the drain retries the person"
+ assert rows[0][4] == 10, "max_version must move to the later sweep, or the drain skips the newer tombstone"
def _foreign_run_dictionary(cluster: ClickhouseCluster, run_id: str) -> clickhouse_cleanup.SnapshotDictionary:
@@ -676,6 +682,33 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_d
assert queue_row() == blocked
assert blocked[2] is not None
+ # A row an older build queued without max_version gets one from a same-run retry; the drain
+ # never deletes a row without one.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET max_version = NULL")
+ persons_database.commit()
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)
+ assert [row[4] for row in queued_rows(persons_database)] == [0]
+
+ # A later run queued the person with a newer bound; this older run's retry must not roll it back,
+ # or the drain skips the newer tombstone and no future sweep queues the person again.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET deleted_at = '2026-02-01T00:00:00Z', max_version = 7")
+ persons_database.commit()
+ newer = queue_row()
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)
+ assert queue_row() == newer
+ assert [row[4] for row in queued_rows(persons_database)] == [7]
+
+ # A run re-executed from a later op keeps its old snapshot but gets a new deleted_at, so it can
+ # arrive after a newer run's row. It moves deleted_at forward and keeps the higher bound.
+ with persons_database.cursor() as cursor:
+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET deleted_at = '2025-12-01T00:00:00Z', max_version = 7")
+ persons_database.commit()
+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)
+ [(_, _, deleted_at, _, max_version)] = queued_rows(persons_database)
+ assert (deleted_at, max_version) == (datetime(2026, 1, 1, tzinfo=UTC), 7)
+
@pytest.mark.django_db
def test_excludes_a_person_revived_while_the_run_is_in_flight(cluster: ClickhouseCluster, persons_database):
@@ -1008,11 +1041,13 @@ def test_more_batches_than_teams_does_not_produce_empty_ranges():
@pytest.mark.django_db
-def test_a_retried_snapshot_populate_cannot_skew_the_dictionary(cluster: ClickhouseCluster):
+def test_a_retried_snapshot_populate_cannot_skew_the_bounds(cluster: ClickhouseCluster, persons_database):
# An op retry re-runs populate, leaving duplicate key rows until a merge collapses them. The
- # dictionary must read the newest max_version bound, not whichever duplicate it happens upon.
+ # dictionary and the queue must read the newest max_version bound, not whichever duplicate
+ # they happen upon.
person = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
- table = clickhouse_cleanup.DeletedPersonsTable(run_id="retry_run")
+ run = clickhouse_cleanup.CleanupRun.for_run("retry_run", clickhouse_cleanup.CleanupConfig(dry_run=False))
+ table = run.persons
populate = partial(table.populate, min_tombstone_age_seconds=0)
cluster.any_host(populate).result()
# The person gains a higher deleted version between the attempt and its retry.
@@ -1020,9 +1055,7 @@ def test_a_retried_snapshot_populate_cannot_skew_the_dictionary(cluster: Clickho
cluster.any_host(populate).result()
cluster.map_all_hosts(table.sync_replica).result()
- dictionary = clickhouse_cleanup.SnapshotDictionary(
- source=table, excluded=clickhouse_cleanup.RevivedPersonsTable(run_id="retry_run")
- )
+ dictionary = clickhouse_cleanup.SnapshotDictionary(source=table, excluded=run.revived)
try:
cluster.map_all_hosts(partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()
cluster.map_all_hosts(dictionary.load, concurrency=1).result()
@@ -1030,6 +1063,12 @@ def test_a_retried_snapshot_populate_cannot_skew_the_dictionary(cluster: Clickho
lambda client: client.execute(f"SELECT person_id, max_version FROM {dictionary.qualified_name}")
).result()
assert rows == [(UUID(person), 3)]
+
+ run = replace(run, distinct_ids_deleted_at=datetime(2026, 1, 1, tzinfo=UTC), persons_count=1)
+ clickhouse_cleanup.persist_deleted_persons(
+ dagster.build_op_context(), cluster, persons_db_url(writer=True), run
+ )
+ assert [row[4] for row in queued_rows(persons_database)] == [3]
finally:
cluster.map_all_hosts(dictionary.drop).result()
cluster.any_host(table.drop_run_partition).result()
@@ -1374,7 +1413,12 @@ def test_a_queue_write_conflict_is_retried_rather_than_failing_the_sweep(pgcode,
monkeypatch.setattr(clickhouse_cleanup, "execute_values", fake_execute_values)
connection = _FakeQueueConnection()
- retries = clickhouse_cleanup._write_queue_page(connection, object(), [(1, "uuid-a")], datetime.now(UTC))
+ retries = clickhouse_cleanup._write_queue_page(
+ connection,
+ object(),
+ [clickhouse_cleanup._QueuedPerson(team_id=1, person_id="uuid-a", max_version=0)],
+ datetime.now(UTC),
+ )
assert retries == 2
assert connection.rollbacks == 2, "an aborted transaction has to be rolled back before the replay"
@@ -1387,7 +1431,12 @@ def test_a_queue_write_error_that_is_not_a_conflict_still_fails_the_sweep(monkey
monkeypatch.setattr(clickhouse_cleanup, "execute_values", fake_execute_values)
with pytest.raises(psycopg2.OperationalError):
- clickhouse_cleanup._write_queue_page(_FakeQueueConnection(), object(), [(1, "uuid-a")], datetime.now(UTC))
+ clickhouse_cleanup._write_queue_page(
+ _FakeQueueConnection(),
+ object(),
+ [clickhouse_cleanup._QueuedPerson(team_id=1, person_id="uuid-a", max_version=0)],
+ datetime.now(UTC),
+ )
def test_persistent_queue_conflicts_give_up_inside_the_retry_window(monkeypatch):
@@ -1401,4 +1450,9 @@ def test_persistent_queue_conflicts_give_up_inside_the_retry_window(monkeypatch)
monkeypatch.setattr(clickhouse_cleanup, "execute_values", always_conflicts)
with pytest.raises(psycopg2.OperationalError):
- clickhouse_cleanup._write_queue_page(_FakeQueueConnection(), object(), [(1, "uuid-a")], datetime.now(UTC))
+ clickhouse_cleanup._write_queue_page(
+ _FakeQueueConnection(),
+ object(),
+ [clickhouse_cleanup._QueuedPerson(team_id=1, person_id="uuid-a", max_version=0)],
+ datetime.now(UTC),
+ )
diff --git a/posthog/dags/tests/test_person_pg_cleanup_drain.py b/posthog/dags/tests/test_person_pg_cleanup_drain.py
index 144e2869c042..b8b1b794b9eb 100644
--- a/posthog/dags/tests/test_person_pg_cleanup_drain.py
+++ b/posthog/dags/tests/test_person_pg_cleanup_drain.py
@@ -42,10 +42,12 @@ OP = "drain_person_pg_cleanup_queue"
FAST = {"pause_ms": 0, "latency_multiplier": 0.0, "retry_backoff_seconds": 0.0}
-def queue(conn, rows: list[tuple[int, str, datetime]]) -> None:
+def queue(conn, rows: list[tuple[int, str, datetime]], max_version: int | None = 0) -> None:
with conn.cursor() as cursor:
cursor.executemany(
- f"INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at) VALUES (%s, %s, %s)", rows
+ f"INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at, max_version) "
+ "VALUES (%s, %s, %s, %s)",
+ [(*row, max_version) for row in rows],
)
conn.commit()
@@ -85,13 +87,14 @@ def failure_of(result: dagster.ExecuteInProcessResult) -> tuple[str, Mapping[str
return failure.user_failure_data.description or "", failure.user_failure_data.metadata
-def seed_tombstoned(fake: FakePersonHogClient, team_id: int, person_id: int) -> str:
+def seed_tombstoned(fake: FakePersonHogClient, team_id: int, person_id: int, version: int = 0) -> str:
uuid = str(uuid4())
distinct_ids = [f"{person_id}-a", f"{person_id}-b"]
fake.add_person(
team_id=team_id,
person_id=person_id,
uuid=uuid,
+ version=version,
distinct_ids=distinct_ids,
is_deleted=True,
tombstoned_distinct_ids=distinct_ids,
@@ -143,6 +146,10 @@ def delete_requests(fake: FakePersonHogClient) -> list:
return [call.request for call in fake.calls if call.method == "delete_tombstoned_persons"]
+def sent_uuids(request: DeleteTombstonedPersonsRequest) -> list[str]:
+ return [person.person_uuid for person in request.bounded_persons]
+
+
def distinct_id_count(fake: FakePersonHogClient, team_id: int, uuid: str) -> int:
person = fake.stored_person(team_id, uuid)
assert person is not None
@@ -210,7 +217,7 @@ def test_deletes_tombstoned_persons_and_removes_their_queue_rows(cluster: Clickh
assert queued(persons_database) == []
requests = delete_requests(fake)
assert sorted(request.team_id for request in requests) == [TEAM_A, TEAM_B]
- assert {uuid for request in requests for uuid in request.person_uuids} == {a1, a2, b1}
+ assert {uuid for request in requests for uuid in sent_uuids(request)} == {a1, a2, b1}
assert all(request.max_rows == drain.STEP_START_ROWS for request in requests)
totals = totals_of(result)
assert (totals.persons_deleted, totals.rows_deleted, totals.queue_rows_deleted) == (3, 6, 3)
@@ -236,6 +243,53 @@ def test_removes_rows_for_live_and_unknown_persons_without_deleting_them(cluster
assert (totals.persons_deleted, totals.persons_skipped_live, totals.persons_not_found) == (1, 1, 1)
+def test_deletes_only_at_or_below_the_version_bound_and_leaves_unversioned_rows_queued(
+ cluster: ClickhouseCluster, persons_database
+):
+ # A person tombstoned again after the sweep still has ClickHouse rows, so its Postgres row stays.
+ # A row without a bound is never sent, because nothing says which versions the sweep removed.
+ fake = get_active_fake()
+ at_bound = seed_tombstoned(fake, TEAM_A, 1, version=3)
+ above = seed_tombstoned(fake, TEAM_A, 2, version=4)
+ unversioned = seed_tombstoned(fake, TEAM_A, 3)
+ queue(persons_database, [(TEAM_A, at_bound, SWEEP_1), (TEAM_A, above, SWEEP_1)], max_version=3)
+ queue(persons_database, [(TEAM_A, unversioned, SWEEP_1)], max_version=None)
+
+ result = run_job(cluster)
+
+ assert not present(fake, TEAM_A, at_bound)
+ assert present(fake, TEAM_A, above) and present(fake, TEAM_A, unversioned)
+ assert queued(persons_database) == [(TEAM_A, unversioned, SWEEP_1, None)]
+ bounds = [(person.person_uuid, person.max_version) for r in delete_requests(fake) for person in r.bounded_persons]
+ assert sorted(bounds) == sorted([(at_bound, 3), (above, 3)])
+ totals = totals_of(result)
+ assert (totals.persons_deleted, totals.persons_skipped_version, totals.persons_not_found) == (1, 1, 0)
+ assert (totals.rows_unversioned, totals.queue_rows_deleted) == (1, 2)
+
+
+def test_a_replica_that_ignores_the_version_bounds_fails_the_run_without_writing(
+ cluster: ClickhouseCluster, persons_database, monkeypatch
+):
+ # A replica without bounded_persons support deletes nothing, and applying its answer would drop every queue row.
+ fake = get_active_fake()
+ gone = seed_tombstoned(fake, TEAM_A, 1)
+ queue(persons_database, [(TEAM_A, gone, SWEEP_1)])
+ monkeypatch.setattr(
+ fake, "delete_tombstoned_persons", lambda request, timeout=None: DeleteTombstonedPersonsResponse()
+ )
+
+ result = run_job(cluster, raise_on_error=False)
+
+ assert not result.success
+ assert queued(persons_database) == [(TEAM_A, gone, SWEEP_1, None)]
+ assert present(fake, TEAM_A, gone)
+ description, metadata = failure_of(result)
+ assert "did not apply the version bounds" in description
+ assert metadata["queue_rows_deleted"].value == 0
+
+
@pytest.mark.django_db
@pytest.mark.parametrize(
"seed,distinct_ids_kept,resends",
@@ -287,7 +341,7 @@ def test_a_person_over_the_budget_is_finished_across_pending_resends_and_small_p
assert not present(fake, TEAM_A, big) and not present(fake, TEAM_A, small)
# Call 1 deletes the small person and leaves the budget spent; calls 2 and 3 trim two rows
# each; call 4 finds one row left, which fits, and deletes the person whole.
- assert [sorted(request.person_uuids) for request in delete_requests(fake)] == [sorted([big, small]), [big]] + [
+ assert [sorted(sent_uuids(request)) for request in delete_requests(fake)] == [sorted([big, small]), [big]] + [
[big]
] * 2
assert (totals.rpc_calls, totals.requests_pending_resent, totals.rows_deleted, totals.persons_deleted) == (
@@ -408,9 +462,9 @@ def test_every_row_is_drained_exactly_once_across_page_and_chunk_boundaries(
result = run_job(cluster, page_size=2, rpc_batch_size=1)
- sent = [uuid for request in delete_requests(fake) for uuid in request.person_uuids]
+ sent = [uuid for request in delete_requests(fake) for uuid in sent_uuids(request)]
assert sorted(sent) == sorted(uuids)
- assert all(len(request.person_uuids) == 1 for request in delete_requests(fake))
+ assert all(len(sent_uuids(request)) == 1 for request in delete_requests(fake))
assert queued(persons_database) == []
assert totals_of(result).pages == 3
@@ -459,7 +513,7 @@ def test_rows_from_two_sweeps_are_sent_separately_and_a_requeued_row_survives(
def requeue_during_rpc(
request: DeleteTombstonedPersonsRequest, timeout: float | None = None
) -> DeleteTombstonedPersonsResponse:
- if requeued in request.person_uuids:
+ if requeued in sent_uuids(request):
with persons_database.cursor() as cursor:
cursor.execute(
f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET deleted_at = %s WHERE person_uuid = ANY(%s::uuid[])",
@@ -472,7 +526,7 @@ def test_rows_from_two_sweeps_are_sent_separately_and_a_requeued_row_survives(
result = run_job(cluster)
- sent = [sorted(request.person_uuids) for request in delete_requests(fake)]
+ sent = [sorted(sent_uuids(request)) for request in delete_requests(fake)]
assert sorted(sent) == sorted([sorted([old, requeued, requeued_blocked]), [new]])
# Both re-queued rows survive untouched: the resolved one is not deleted, and the blocked one is
# not stamped, because both now belong to the newer sweep.
@@ -721,34 +775,36 @@ def test_queue_statement_failures_reconnect_and_retry_inside_the_window(
([], 3, []),
(
[
- QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1),
- QueueRow(team_id=1, person_uuid="b", deleted_at=SWEEP_1),
+ QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1, max_version=1),
+ QueueRow(team_id=1, person_uuid="b", deleted_at=SWEEP_1, max_version=2),
+ QueueRow(team_id=1, person_uuid="c", deleted_at=SWEEP_1, max_version=None),
],
3,
- [Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a", "b"))],
+ [Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a", "b"), max_versions={"a": 1, "b": 2})],
),
(
[
- QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1),
- QueueRow(team_id=1, person_uuid="b", deleted_at=SWEEP_2),
- QueueRow(team_id=2, person_uuid="c", deleted_at=SWEEP_1),
+ QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1, max_version=1),
+ QueueRow(team_id=1, person_uuid="b", deleted_at=SWEEP_2, max_version=2),
+ QueueRow(team_id=2, person_uuid="c", deleted_at=SWEEP_1, max_version=3),
],
3,
[
- Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a",)),
- Chunk(team_id=1, deleted_at=SWEEP_2, person_uuids=("b",)),
- Chunk(team_id=2, deleted_at=SWEEP_1, person_uuids=("c",)),
+ Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a",), max_versions={"a": 1}),
+ Chunk(team_id=1, deleted_at=SWEEP_2, person_uuids=("b",), max_versions={"b": 2}),
+ Chunk(team_id=2, deleted_at=SWEEP_1, person_uuids=("c",), max_versions={"c": 3}),
],
),
(
- [QueueRow(team_id=1, person_uuid=uuid, deleted_at=SWEEP_1) for uuid in "abcde"],
+ [QueueRow(team_id=1, person_uuid=uuid, deleted_at=SWEEP_1, max_version=0) for uuid in "abcde"],
2,
[
- Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a", "b")),
- Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("c", "d")),
- Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("e",)),
+ Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a", "b"), max_versions={"a": 0, "b": 0}),
+ Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("c", "d"), max_versions={"c": 0, "d": 0}),
+ Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("e",), max_versions={"e": 0}),
],
),
+ ([QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1, max_version=None)], 3, []),
],
)
def test_chunks_for_page_groups_by_team_and_sweep_then_splits(rows, rpc_batch_size, expected):
@@ -842,10 +898,12 @@ def test_publishes_every_measurement_the_run_took():
rows_read=5,
persons_deleted=3,
persons_skipped_live=2,
+ persons_skipped_version=6,
persons_not_found=7,
persons_blocked=1,
rows_deleted=40,
rows_stamped_blocked=1,
+ rows_unversioned=8,
requests_pending_resent=4,
queue_rows_estimate_at_start=1000,
step_rows_min=250,
@@ -865,10 +923,12 @@ def test_publishes_every_measurement_the_run_took():
"rows_read",
"persons_deleted",
"persons_skipped_live",
+ "persons_skipped_version",
"persons_not_found",
"persons_blocked",
"rows_deleted",
"rows_stamped_blocked",
+ "rows_unversioned",
"requests_pending_resent",
"step_rows_min",
"rpc_errors",
@@ -880,10 +940,12 @@ def test_publishes_every_measurement_the_run_took():
"rows_read": 5,
"persons_deleted": 3,
"persons_skipped_live": 2,
+ "persons_skipped_version": 6,
"persons_not_found": 7,
"persons_blocked": 1,
"rows_deleted": 40,
"rows_stamped_blocked": 1,
+ "rows_unversioned": 8,
"requests_pending_resent": 4,
"step_rows_min": 250,
"rpc_errors": 2,