:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(persons): resolve the person tombstone queue in the deletion sweep (#105640)
Nick Best9deb80c6df84
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex ad44b8081d2d..2fafc4b1bd2c 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -48,6 +48,7 @@ from posthog.dags.common.staged_dictionary import (load_and_verify_on_every_cluster,)from posthog.dags.deletes import deletes_job+from posthog.dags.person_tombstone_queue import publish_queue_gauges, resolve_person_tombstone_queuefrom posthog.dataclasses import frozenfrom posthog.metrics import pushed_metrics_registryfrom posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions@@ -553,6 +554,52 @@ def _create_dictionary(return dictionary+class TombstoneQueueConfig(dagster.Config):+ visibility_timeout_seconds: int = 600+ poll_interval_seconds: int = 15+++def resolve_tombstone_queue(+ context: dagster.OpExecutionContext,+ config: TombstoneQueueConfig,+ run: CleanupRun,+) -> CleanupRun:+ try:+ result = resolve_person_tombstone_queue(+ dry_run=run.dry_run,+ min_team_id=run.min_team_id,+ max_team_id=run.max_team_id,+ visibility_timeout_seconds=config.visibility_timeout_seconds,+ poll_interval_seconds=config.poll_interval_seconds,+ log=context.log.warning,+ )+ if not run.dry_run:+ publish_queue_gauges(result, time.time())+ except Exception:+ context.log.exception("resolving the person tombstone queue failed, continuing with the sweep")+ return run++ if result.failed_teams:+ context.log.warning("%s teams could not be resolved after retries; their rows stay queued", result.failed_teams)+ if result.remaining:+ context.log.warning(+ "persons deleted in Postgres but not confirmed deleted in ClickHouse: %s",+ ", ".join(f"{row.team_id}:{row.person_uuid}" for row in result.remaining),+ )+ context.add_output_metadata(+ {+ "listed": dagster.MetadataValue.int(result.listed),+ "dropped": dagster.MetadataValue.int(result.dropped),+ "confirmed": dagster.MetadataValue.int(result.confirmed),+ "republished": dagster.MetadataValue.int(result.republished),+ "failed_teams": dagster.MetadataValue.int(result.failed_teams),+ "remaining": dagster.MetadataValue.int(len(result.remaining)),+ }+ )+ return run++@dagster.opdef clear_removed_cohort_data(context: dagster.OpExecutionContext,@@ -1505,7 +1552,7 @@ def drop_assets_on_failure(context: dagster.HookContext) -> None:)def clickhouse_deletion_sweep_job():"""Sweep deleted cohort memberships, then deleted persons and their distinct ids."""- run = snapshot_orphaned_distinct_ids(snapshot_deleted_persons(clear_removed_cohort_data()))+ run = snapshot_orphaned_distinct_ids(snapshot_deleted_persons(resolve_tombstone_queue(clear_removed_cohort_data())))run = recheck_revived_persons("recheck_before_distinct_id_delete")(run)run = delete_orphaned_distinct_ids(run)@@ -1548,7 +1595,13 @@ SCHEDULED_RUN_CONFIG = {"min_team_id": 0,"max_team_id": 0,}- }+ },+ "resolve_tombstone_queue": {+ "config": {+ "visibility_timeout_seconds": 600,+ "poll_interval_seconds": 15,+ }+ },}}diff --git a/posthog/dags/person_tombstone_queue.py b/posthog/dags/person_tombstone_queue.pynew file mode 100644index 000000000000..dc6f1c72fcf1--- /dev/null+++ b/posthog/dags/person_tombstone_queue.py@@ -0,0 +1,269 @@+import time+from collections import defaultdict+from collections.abc import Callable, Sequence+from dataclasses import field+from functools import partial+from typing import TypeVar+from uuid import UUID++from prometheus_client import Gauge++from posthog.clickhouse.client import sync_execute+from posthog.dataclasses import frozen+from posthog.kafka_client.routing import flush_all_producers+from posthog.metrics import pushed_metrics_registry+from posthog.models.person.util import (+ PersonTombstone,+ QueuedPersonTombstone,+ ack_person_tombstones,+ get_person_tombstones,+ list_person_tombstone_queue,+ publish_person_tombstone,+)++METRICS_JOB = "person_tombstone_queue"+PAGE_SIZE = 1000+CHUNK_SIZE = 100+FLUSH_TIMEOUT_SECONDS = 60+# A team's pass is retried before the team is given up on. The sweep runs weekly, so a team that+# stays broken waits for the next run rather than holding the whole queue.+TEAM_ATTEMPTS = 3+RETRY_BACKOFF_SECONDS = 5++_T = TypeVar("_T")+++@frozen(frozen=False)+class QueueResolution:+ listed: int = 0+ dropped: int = 0+ confirmed: int = 0+ republished: int = 0+ # Teams whose queue could not be resolved after TEAM_ATTEMPTS. Their rows stay queued and count+ # as remaining.+ failed_teams: int = 0+ remaining: list[QueuedPersonTombstone] = field(default_factory=list)+++@frozen+class _TeamPass:+ dropped: int+ confirmed: int+ pending: dict[UUID, PersonTombstone]+++def _with_retries(fn: Callable[[], _T]) -> _T:+ for attempt in range(TEAM_ATTEMPTS):+ try:+ return fn()+ except Exception:+ if attempt == TEAM_ATTEMPTS - 1:+ raise+ time.sleep(RETRY_BACKOFF_SECONDS * 2**attempt)+ raise AssertionError("unreachable")+++def _in_range(team_id: int, min_team_id: int, max_team_id: int) -> bool:+ return (not min_team_id or team_id >= min_team_id) and (not max_team_id or team_id <= max_team_id)+++def _list_queue(min_team_id: int, max_team_id: int) -> list[QueuedPersonTombstone]:+ rows: list[QueuedPersonTombstone] = []+ after: tuple[int, UUID] | None = None+ while page := list_person_tombstone_queue(after, PAGE_SIZE):+ rows.extend(row for row in page if _in_range(row.team_id, min_team_id, max_team_id))+ after = (page[-1].team_id, page[-1].person_uuid)+ return rows+++def _is_shown(row: tuple[int, int] | None, version: int) -> bool:+ # A missing row is not confirmation: the live row can still be in flight through Kafka, and+ # acking now would leave nothing queued to delete it when it lands.+ if row is None:+ return False+ is_deleted, max_version = row+ return max_version > version or (bool(is_deleted) and max_version >= version)+++def clickhouse_confirmed(team_id: int, tombstones: Sequence[PersonTombstone]) -> set[UUID]:+ if not tombstones:+ return set()+ persons = {+ str(person_id): (is_deleted, max_version)+ for person_id, is_deleted, max_version in sync_execute(+ """+ SELECT id, argMax(is_deleted, version), max(version)+ FROM person+ WHERE team_id = %(team_id)s AND id IN %(ids)s+ GROUP BY id+ """,+ {"team_id": team_id, "ids": [str(t.uuid) for t in tombstones]},+ )+ }+ distinct_ids = [d.id for t in tombstones for d in t.distinct_ids]+ mappings = (+ {+ distinct_id: (is_deleted, max_version)+ for distinct_id, is_deleted, max_version in sync_execute(+ """+ SELECT distinct_id, argMax(is_deleted, version), max(version)+ FROM person_distinct_id2+ WHERE team_id = %(team_id)s AND distinct_id IN %(distinct_ids)s+ GROUP BY distinct_id+ """,+ {"team_id": team_id, "distinct_ids": distinct_ids},+ )+ }+ if distinct_ids+ else {}+ )+ return {+ t.uuid+ for t in tombstones+ if _is_shown(persons.get(str(t.uuid)), t.version)+ and all(_is_shown(mappings.get(d.id), d.version) for d in t.distinct_ids)+ }+++def _confirm_and_ack(team_id: int, tombstones: dict[UUID, PersonTombstone]) -> int:+ """Ack the queued persons ClickHouse shows as deleted, a chunk at a time, and drop them from ``tombstones``."""+ batch = list(tombstones.values())+ acked = 0+ for i in range(0, len(batch), CHUNK_SIZE):+ confirmed = clickhouse_confirmed(team_id, batch[i : i + CHUNK_SIZE])+ if not confirmed:+ continue+ ack_person_tombstones(team_id, [(uuid, tombstones[uuid].version) for uuid in confirmed])+ acked += len(confirmed)+ for uuid in confirmed:+ del tombstones[uuid]+ return acked+++def _resolve_team(team_id: int, team_rows: Sequence[QueuedPersonTombstone], *, dry_run: bool) -> _TeamPass:+ """Ack the rows ClickHouse already shows as deleted, or that no longer exist, and return the rest.++ Acks as it goes, so a retry after a failed chunk re-confirms the acked rows without harm: the+ ack is idempotent, and the counts come from this pass alone.+ """+ dropped = confirmed_count = 0+ pending: dict[UUID, PersonTombstone] = {}+ for i in range(0, len(team_rows), CHUNK_SIZE):+ chunk = team_rows[i : i + CHUNK_SIZE]+ stored = {t.uuid: t for t in get_person_tombstones(team_id, [row.person_uuid for row in chunk])}+ gone = [(row.person_uuid, row.person_version) for row in chunk if row.person_uuid not in stored]+ confirmed = clickhouse_confirmed(team_id, list(stored.values()))+ dropped += len(gone)+ confirmed_count += len(confirmed)+ if not dry_run:+ ack_person_tombstones(team_id, gone + [(uuid, stored[uuid].version) for uuid in confirmed])+ for uuid, tombstone in stored.items():+ if uuid not in confirmed:+ pending[uuid] = tombstone+ return _TeamPass(dropped=dropped, confirmed=confirmed_count, pending=pending)+++def resolve_person_tombstone_queue(+ *,+ dry_run: bool,+ min_team_id: int,+ max_team_id: int,+ visibility_timeout_seconds: int,+ poll_interval_seconds: int,+ log: Callable[[str], None],+) -> QueueResolution:+ """Resolve every queued tombstone in the team range, one team at a time.++ A team whose pass keeps failing is logged, counted in ``failed_teams`` and left queued for the+ next run. No single failure stops the other teams or the sweep that runs after this.+ """+ result = QueueResolution()+ queued = _list_queue(min_team_id, max_team_id)+ result.listed = len(queued)+ by_team: dict[int, list[QueuedPersonTombstone]] = defaultdict(list)+ for row in queued:+ by_team[row.team_id].append(row)++ pending: dict[int, dict[UUID, PersonTombstone]] = {}+ failed: list[QueuedPersonTombstone] = []+ row_for: dict[tuple[int, UUID], QueuedPersonTombstone] = {(row.team_id, row.person_uuid): row for row in queued}+ for team_id, team_rows in by_team.items():+ try:+ team_pass = _with_retries(partial(_resolve_team, team_id, team_rows, dry_run=dry_run))+ except Exception as exc:+ log(+ f"team {team_id}: resolving its tombstone queue failed {TEAM_ATTEMPTS} times: {type(exc).__name__}: {exc}"+ )+ result.failed_teams += 1+ failed.extend(team_rows)+ continue+ result.dropped += team_pass.dropped+ result.confirmed += team_pass.confirmed+ if team_pass.pending:+ pending[team_id] = team_pass.pending++ if dry_run:+ result.republished = sum(len(p) for p in pending.values())+ result.remaining = [row_for[(team_id, uuid)] for team_id, p in pending.items() for uuid in p] + failed+ return result++ for team_id, tombstones in pending.items():+ for tombstone in tombstones.values():+ try:+ publish_person_tombstone(team_id, tombstone)+ result.republished += 1+ except Exception as exc:+ log(f"publishing the tombstone for person {tombstone.uuid} failed: {type(exc).__name__}: {exc}")+ undelivered = flush_all_producers(FLUSH_TIMEOUT_SECONDS)+ if undelivered:+ log(f"{undelivered} Kafka messages were not delivered")++ deadline = time.monotonic() + visibility_timeout_seconds+ while True:+ for team_id in list(pending):+ try:+ result.confirmed += _with_retries(partial(_confirm_and_ack, team_id, pending[team_id]))+ except Exception as exc:+ log(+ f"team {team_id}: confirming its republished tombstones failed {TEAM_ATTEMPTS} times: {type(exc).__name__}: {exc}"+ )+ result.failed_teams += 1+ failed.extend(row_for[(team_id, uuid)] for uuid in pending.pop(team_id))+ continue+ if not pending[team_id]:+ del pending[team_id]+ if not pending or time.monotonic() >= deadline:+ break+ time.sleep(poll_interval_seconds)++ result.remaining = [+ row_for[(team_id, uuid)] for team_id, tombstones in pending.items() for uuid in tombstones+ ] + failed+ return result+++def publish_queue_gauges(result: QueueResolution, completed_at: float) -> None:+ """Publish what the run measured. Only a completed run reaches here: a run that could not list+ the queue publishes nothing, so a staleness alert on the last-run gauge is what reports it."""+ oldest_ms = min((row.tombstoned_at_ms for row in result.remaining), default=None)+ with pushed_metrics_registry(METRICS_JOB) as registry:+ Gauge(+ "posthog_person_tombstone_queue_unresolved_rows",+ "Queued persons the weekly repair could not confirm in ClickHouse: deleted in Postgres, possibly live in ClickHouse",+ registry=registry,+ ).set(len(result.remaining))+ Gauge(+ "posthog_person_tombstone_queue_failed_teams",+ "Teams whose queue the weekly repair gave up on after retries; their rows stay queued",+ registry=registry,+ ).set(result.failed_teams)+ Gauge(+ "posthog_person_tombstone_queue_oldest_unresolved_seconds",+ "Age of the oldest queued person the weekly repair could not confirm",+ registry=registry,+ ).set(completed_at - oldest_ms / 1000 if oldest_ms is not None else 0)+ Gauge(+ "posthog_person_tombstone_queue_last_run_timestamp_seconds",+ "Unix time when the weekly repair last finished",+ registry=registry,+ ).set(completed_at)diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.pyindex 71f6e4cf4610..6f0ef17346c4 100644--- a/posthog/dags/tests/test_clickhouse_cleanup.py+++ b/posthog/dags/tests/test_clickhouse_cleanup.py@@ -1095,11 +1095,20 @@ def test_the_job_carries_the_operational_tags():assert int(tags["dagster/max_runtime"]) == 43200-def test_the_scheduled_config_pins_every_setting_the_sweep_reads():+ "op_name,config_class",+ [+ ("clear_removed_cohort_data", clickhouse_cleanup.CleanupConfig),+ ("resolve_tombstone_queue", clickhouse_cleanup.TombstoneQueueConfig),+ ],+)+def test_the_scheduled_config_pins_every_setting_the_sweep_reads(+ op_name: str, config_class: type[dagster.Config]+) -> None:# A field added to CleanupConfig without a scheduled value would run production on whatever# the code default happens to be, which is exactly what pinning this config prevents.- pinned = set(SCHEDULED_RUN_CONFIG["ops"]["clear_removed_cohort_data"]["config"])- declared = set(clickhouse_cleanup.CleanupConfig.model_fields)+ pinned = set(SCHEDULED_RUN_CONFIG["ops"][op_name]["config"])+ declared = set(config_class.model_fields)assert declared == pinneddiff --git a/posthog/dags/tests/test_person_tombstone_queue.py b/posthog/dags/tests/test_person_tombstone_queue.pynew file mode 100644index 000000000000..944ad5638463--- /dev/null+++ b/posthog/dags/tests/test_person_tombstone_queue.py@@ -0,0 +1,269 @@+from contextlib import contextmanager+from uuid import UUID, uuid4++import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patch++import dagster+from parameterized import parameterized+from prometheus_client import CollectorRegistry++from posthog.clickhouse.client import sync_execute+from posthog.dags import clickhouse_cleanup+from posthog.dags.person_tombstone_queue import (+ TEAM_ATTEMPTS,+ QueueResolution,+ clickhouse_confirmed,+ publish_queue_gauges,+ resolve_person_tombstone_queue,+)+from posthog.models import Team+from posthog.models.person.util import (+ PersonTombstone,+ QueuedPersonTombstone,+ create_person as create_person_in_ch,+ publish_person_tombstone,+ tombstone_persons_in_postgres,+)+from posthog.personhog_client.fake_client import get_active_fake+from posthog.test.persons import create_person+++class TestResolvePersonTombstoneQueue(ClickhouseTestMixin, BaseTest):+ def _tombstoned(self, distinct_id: str, *, published: bool) -> UUID:+ person = create_person(team_id=self.team.pk, distinct_ids=[distinct_id])+ [tombstone] = tombstone_persons_in_postgres(self.team.pk, [person.uuid])+ if published:+ publish_person_tombstone(self.team.pk, tombstone)+ return person.uuid++ def _resolve(self, *, dry_run: bool = False, min_team_id: int = 0, max_team_id: int = 0) -> QueueResolution:+ return resolve_person_tombstone_queue(+ dry_run=dry_run,+ min_team_id=min_team_id,+ max_team_id=max_team_id,+ visibility_timeout_seconds=0,+ poll_interval_seconds=0,+ log=lambda _: None,+ )++ def _queued(self) -> set[UUID]:+ return {UUID(person_uuid) for _, person_uuid in get_active_fake().tombstone_queue}++ def _ch_person_deleted(self, person_uuid: UUID) -> bool:+ [[is_deleted]] = sync_execute(+ "SELECT argMax(is_deleted, version) FROM person WHERE team_id = %(t)s AND id = %(u)s",+ {"t": self.team.pk, "u": str(person_uuid)},+ )+ return bool(is_deleted)++ def test_confirms_republishes_and_drops_queued_persons(self) -> None:+ confirmed = self._tombstoned("queue-confirmed", published=True)+ behind = self._tombstoned("queue-behind", published=False)+ live = create_person(team_id=self.team.pk, distinct_ids=["queue-live"]).uuid+ missing = uuid4()+ get_active_fake().tombstone_queue[(self.team.pk, str(live))] = 1+ get_active_fake().tombstone_queue[(self.team.pk, str(missing))] = 1++ result = self._resolve()++ assert (result.listed, result.dropped, result.confirmed, result.republished) == (4, 2, 2, 1)+ assert result.remaining == []+ assert self._queued() == set()+ assert self._ch_person_deleted(confirmed)+ assert self._ch_person_deleted(behind)+ assert not self._ch_person_deleted(live)++ def test_a_live_distinct_id_keeps_the_person_queued(self) -> None:+ person = create_person(team_id=self.team.pk, distinct_ids=["queue-did"])+ [tombstone] = tombstone_persons_in_postgres(self.team.pk, [person.uuid])+ create_person_in_ch(uuid=str(person.uuid), team_id=self.team.pk, version=tombstone.version, is_deleted=True)++ with patch("posthog.dags.person_tombstone_queue.publish_person_tombstone") as publish:+ result = self._resolve()++ publish.assert_called_once_with(self.team.pk, tombstone)+ assert [row.person_uuid for row in result.remaining] == [person.uuid]+ assert self._queued() == {person.uuid}++ def test_dry_run_acks_and_publishes_nothing(self) -> None:+ confirmed = self._tombstoned("queue-dry-confirmed", published=True)+ behind = self._tombstoned("queue-dry-behind", published=False)++ result = self._resolve(dry_run=True)++ assert [row.person_uuid for row in result.remaining] == [behind]+ assert self._queued() == {confirmed, behind}+ assert not self._ch_person_deleted(behind)++ def test_leaves_teams_outside_the_range_alone(self) -> None:+ behind = self._tombstoned("queue-range", published=False)++ result = self._resolve(min_team_id=self.team.pk + 1)++ assert result.listed == 0+ assert self._queued() == {behind}+ assert not self._ch_person_deleted(behind)++ def test_a_person_absent_from_clickhouse_is_republished_not_acked(self) -> None:+ person_uuid = uuid4()+ # Persons DB only: the ClickHouse rows for this person are still in flight.+ get_active_fake().add_person(+ team_id=self.team.pk, person_id=1_000_001, uuid=str(person_uuid), distinct_ids=["queue-absent"]+ )+ tombstone_persons_in_postgres(self.team.pk, [person_uuid])++ result = self._resolve()++ assert (result.republished, result.confirmed) == (1, 1)+ assert result.remaining == []+ assert self._queued() == set()+ assert self._ch_person_deleted(person_uuid)++ def test_polls_the_confirmation_in_chunks(self) -> None:+ for i in range(3):+ self._tombstoned(f"queue-chunk-{i}", published=False)++ with (+ patch("posthog.dags.person_tombstone_queue.CHUNK_SIZE", 2),+ patch("posthog.dags.person_tombstone_queue.clickhouse_confirmed", wraps=clickhouse_confirmed) as confirm,+ ):+ result = self._resolve()++ assert (result.republished, result.confirmed) == (3, 3)+ assert self._queued() == set()+ assert max(len(call.args[1]) for call in confirm.call_args_list) == 2++ @parameterized.expand([("transient", 1, 0), ("persistent", TEAM_ATTEMPTS, 1)])+ def test_retries_a_failing_team_and_leaves_it_queued_when_it_keeps_failing(+ self, _name: str, failures: int, failed_teams: int+ ) -> None:+ other = Team.objects.create(organization=self.organization)+ ours = self._tombstoned("queue-ours", published=True)+ theirs = create_person(team=other, distinct_ids=["queue-theirs"])+ tombstone_persons_in_postgres(other.pk, [theirs.uuid])+ raised = 0++ def flaky(team_id: int, tombstones: list) -> set[UUID]:+ nonlocal raised+ if team_id == other.pk and raised < failures:+ raised += 1+ raise RuntimeError("clickhouse down")+ return clickhouse_confirmed(team_id, tombstones)++ with (+ patch("posthog.dags.person_tombstone_queue.clickhouse_confirmed", side_effect=flaky),+ patch("posthog.dags.person_tombstone_queue.RETRY_BACKOFF_SECONDS", 0),+ ):+ result = self._resolve()++ # Our team is unaffected by the other team's failure.+ assert result.failed_teams == failed_teams+ assert ours not in self._queued()+ if failed_teams:+ assert [(row.team_id, row.person_uuid) for row in result.remaining] == [(other.pk, theirs.uuid)]+ assert self._queued() == {theirs.uuid}+ else:+ assert result.remaining == []+ assert self._queued() == set()++ def test_one_failed_publish_leaves_only_that_person_queued(self) -> None:+ failing = self._tombstoned("queue-publish-fails", published=False)+ passing = self._tombstoned("queue-publish-passes", published=False)+ logged: list[str] = []++ def publish(team_id: int, tombstone: PersonTombstone) -> list:+ if tombstone.uuid == failing:+ raise RuntimeError("kafka down")+ return publish_person_tombstone(team_id, tombstone)++ with patch("posthog.dags.person_tombstone_queue.publish_person_tombstone", side_effect=publish):+ result = resolve_person_tombstone_queue(+ dry_run=False,+ min_team_id=0,+ max_team_id=0,+ visibility_timeout_seconds=0,+ poll_interval_seconds=0,+ log=logged.append,+ )++ assert (result.republished, result.confirmed, result.failed_teams) == (1, 1, 0)+ assert [row.person_uuid for row in result.remaining] == [failing]+ assert self._queued() == {failing}+ assert self._ch_person_deleted(passing)+ assert any(str(failing) in line for line in logged)++ def test_pages_through_the_whole_queue(self) -> None:+ behind = {self._tombstoned(f"queue-page-{i}", published=False) for i in range(3)}++ with patch("posthog.dags.person_tombstone_queue.PAGE_SIZE", 2):+ result = self._resolve()++ # Two full pages, then the empty one that ends the walk.+ get_active_fake().assert_called("list_person_tombstone_queue", times=3)+ assert (result.listed, result.republished, result.confirmed) == (3, 3, 3)+ assert self._queued() == set()+ assert all(self._ch_person_deleted(uuid) for uuid in behind)++ def test_remaining_rows_keep_their_own_team(self) -> None:+ other = Team.objects.create(organization=self.organization)+ shared = uuid4()+ for team in (self.team, other):+ person = create_person(team=team, distinct_ids=[f"queue-shared-{team.pk}"], uuid=shared)+ tombstone_persons_in_postgres(team.pk, [person.uuid])++ with patch("posthog.dags.person_tombstone_queue.publish_person_tombstone"):+ result = self._resolve()++ assert sorted((row.team_id, row.person_uuid) for row in result.remaining) == sorted(+ [(self.team.pk, shared), (other.pk, shared)]+ )+++def _queued_row(team_id: int, tombstoned_at_ms: int) -> QueuedPersonTombstone:+ return QueuedPersonTombstone(+ team_id=team_id, person_uuid=uuid4(), person_version=1, tombstoned_at_ms=tombstoned_at_ms+ )+++ "remaining,failed_teams,expected_unresolved,expected_oldest_age",+ [+ ([], 0, 0, 0),+ ([_queued_row(1, 400_000), _queued_row(2, 100_000)], 1, 2, 900),+ ],+)+def test_publishes_the_gauges_the_alert_reads(+ remaining: list[QueuedPersonTombstone],+ failed_teams: int,+ expected_unresolved: int,+ expected_oldest_age: float,+) -> None:+ registry = CollectorRegistry()++ @contextmanager+ def capture(job_name: str):+ assert job_name == "person_tombstone_queue"+ yield registry++ with patch("posthog.dags.person_tombstone_queue.pushed_metrics_registry", capture):+ publish_queue_gauges(QueueResolution(remaining=remaining, failed_teams=failed_teams), completed_at=1_000.0)++ assert registry.get_sample_value("posthog_person_tombstone_queue_unresolved_rows") == expected_unresolved+ assert registry.get_sample_value("posthog_person_tombstone_queue_failed_teams") == failed_teams+ assert registry.get_sample_value("posthog_person_tombstone_queue_oldest_unresolved_seconds") == expected_oldest_age+ assert registry.get_sample_value("posthog_person_tombstone_queue_last_run_timestamp_seconds") == 1_000.0++[email protected]("failing", ["resolve_person_tombstone_queue", "publish_queue_gauges"])+def test_a_queue_failure_does_not_fail_the_sweep(failing: str) -> None:+ run = clickhouse_cleanup.CleanupRun.for_run("run", clickhouse_cleanup.CleanupConfig(dry_run=False))+ context = dagster.build_op_context(op_config={"visibility_timeout_seconds": 0, "poll_interval_seconds": 0})++ with (+ patch.object(clickhouse_cleanup, "resolve_person_tombstone_queue", return_value=QueueResolution()),+ patch.object(clickhouse_cleanup, "publish_queue_gauges"),+ patch.object(clickhouse_cleanup, failing, side_effect=RuntimeError("down")),+ ):+ assert clickhouse_cleanup.resolve_tombstone_queue(context, run=run) == run