: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(clickhouse): add person_pg_cleanup_drain_job (#97995)
Eli Reisman3aedcaccdcd3
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 315a97a1f9fe..e36468fa82e9 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -157,6 +157,7 @@ jobs:- 'posthog/llm/**'- 'posthog/person_db_router.py'- 'posthog/persons_db.py'+ - 'posthog/personhog_client/**'- 'posthog/redis.py'- 'posthog/storage/**'- 'posthog/event_usage.py'diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex aa2df7ae4671..9b980807f6d5 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -1234,7 +1234,7 @@ SWEEP_METRICS_JOB = "clickhouse_deletion_sweep"@frozen-class SweepGauge:+class PublishedGauge:"""One published measurement. Named so the metric name and its help text cannot swap."""name: str@@ -1246,44 +1246,44 @@ class SweepGauge:object.__setattr__(self, "value", float(self.value))-def _sweep_gauges(run: CleanupRun, completed_at: float) -> list[SweepGauge]:+def _sweep_gauges(run: CleanupRun, completed_at: float) -> list[PublishedGauge]:return [- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_last_success_timestamp_seconds",help_text="Unix time when the sweep last finished deleting persons",value=completed_at,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_snapshot_deleted_persons",help_text="Soft-deleted persons this run snapshotted. Saturates at the max_persons cap",value=run.persons_count,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_snapshot_orphaned_distinct_ids",help_text="Orphaned distinct id mappings this run snapshotted, under the same cap",value=run.orphaned_count,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_revived_persons",help_text="Persons that came back between the snapshot and the delete, and were excluded",value=run.revived_person_count,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_revived_distinct_ids",help_text="Distinct id mappings that came back mid-run, and were excluded",value=run.revived_distinct_id_count,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_queued_for_postgres",help_text="Persons handed to the Postgres cleanup queue by this run",value=run.queued_for_postgres,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_mutation_seconds_max",help_text="Slowest single delete mutation of the run, against mutation_wait_deadline",value=run.mutation_seconds_max,),- SweepGauge(+ PublishedGauge(name="posthog_clickhouse_deletion_sweep_stranded_runs_reaped",help_text="Finished runs whose leftover dictionaries this run dropped",value=run.stranded_runs_reaped,diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex 759779218101..8d9bafa3c396 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -16,6 +16,7 @@ from posthog.dags import (orm_examples,part_breaker,person_overrides,+ person_pg_cleanup_drain,postgres_to_clickhouse_etl,property_definitions,)@@ -45,6 +46,7 @@ defs = dagster.Definitions(fix_person_id_overrides.fix_person_id_overrides_job,person_overrides.cleanup_orphaned_person_overrides_snapshot,person_overrides.squash_person_overrides,+ person_pg_cleanup_drain.person_pg_cleanup_drain_job,postgres_to_clickhouse_etl.postgres_to_clickhouse_etl_job,property_definitions.property_definitions_ingestion_job,backups.sharded_backup,diff --git a/posthog/dags/person_pg_cleanup_drain.py b/posthog/dags/person_pg_cleanup_drain.pynew file mode 100644index 000000000000..2864a8ce2277--- /dev/null+++ b/posthog/dags/person_pg_cleanup_drain.py@@ -0,0 +1,899 @@+"""Drain person_pg_cleanup_queue into Postgres hard deletes.++The ClickHouse sweep (clickhouse_cleanup.py) removes a deleted person's rows from ClickHouse and+queues the person here. Postgres still holds the tombstoned posthog_person row and its dependent+rows (distinct ids, hash key overrides, cohort memberships) until this job asks personhog to+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.+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+a person of any size is deleted in steps that each fit the router's deadline; run time is what+gives. Queue rows are removed once personhog has resolved the person either way.++A run fails only when a dependency is down or broken: a request that keeps failing for the whole+retry window, a Postgres statement that keeps failing for its window (a lost connection is+reopened and the statement run again), a fatal gRPC code, or more blocked persons than+max_blocked. The one state the job parks is a tombstoned person that still owns a live distinct+id: personhog reports it as blocked, and its row is stamped blocked_at and skipped for a retry+interval, because ingestion can still reach that person and no delete may resolve it.+"""++import math+import time+from collections import defaultdict+from collections.abc import Callable, Iterator, Mapping, Sequence+from dataclasses import field+from datetime import UTC, datetime, timedelta+from functools import partial+from typing import Literal, TypeVar++import grpc+import dagster+import psycopg2+import pydantic+import psycopg2.extensions+from prometheus_client import Gauge++from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.custom_metrics import MetricsClient+from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE, PublishedGauge+from posthog.dags.common import JobOwners+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++logger = dagster.get_dagster_logger(__name__)++PERSONHOG_CALLER_TAG = "clickhouse_cleanup/person-pg-drain"+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.+RPC_MAX_UUIDS = 1000++# personhog-router caps every backend call at BACKEND_TIMEOUT_MS whatever the client deadline. The+# replica deletes at most REPLICA_CHUNK_SIZE persons per call (its BULK_CHUNK_SIZE) and clamps the+# row budget to REPLICA_MAX_ROWS (its TOMBSTONED_DELETE_MAX_ROWS).+ROUTER_BACKEND_TIMEOUT_SECONDS = 5.0+REPLICA_CHUNK_SIZE = 100+REPLICA_MAX_ROWS = 5000++# Dependent rows per request: start here, halve after a timeout down to the floor, double after+# STEP_GROWTH_SUCCESSES requests in a row succeeded. The persons tables cost up to 5 ms per row at+# the tail, so the floor still fits the router's deadline on a bad day.+STEP_START_ROWS = 500+STEP_FLOOR_ROWS = 100+STEP_GROWTH_SUCCESSES = 20++RETRY_BACKOFF_CAP_SECONDS = 60.0+PG_RETRY_BACKOFF_SECONDS = 1.0+LOG_EVERY_PAGES = 10+BLOCKED_SAMPLE_SIZE = 50++# Codes that say the request itself is wrong or unserved; another attempt returns the same answer.+FATAL_RPC_CODES = frozenset(+ {+ grpc.StatusCode.UNIMPLEMENTED,+ grpc.StatusCode.INVALID_ARGUMENT,+ grpc.StatusCode.PERMISSION_DENIED,+ grpc.StatusCode.UNAUTHENTICATED,+ }+)+# Codes a request that outran the router's deadline comes back with: the router answers+# UNAVAILABLE once its own retries of the backend call time out.+SLOW_RPC_CODES = frozenset({grpc.StatusCode.DEADLINE_EXCEEDED, grpc.StatusCode.UNAVAILABLE})++_T = TypeVar("_T")+++class DrainConfig(dagster.Config):+ dry_run: bool = pydantic.Field(+ default=True,+ description="Page and count the queue without calling personhog or writing to Postgres.",+ )+ max_persons: int = pydantic.Field(+ default=0,+ description="Stop after reading this many queue rows, 0 for no cap. A capped run leaves the rest for the "+ "next run.",+ )+ page_size: int = pydantic.Field(default=1000, description="Queue rows per Postgres read, at most 1000.")+ rpc_batch_size: int = pydantic.Field(+ default=REPLICA_CHUNK_SIZE,+ description="Person uuids per personhog request, at most 1000. The replica deletes at most 100 persons per "+ "call and returns the rest as pending, so more only adds re-sends.",+ )+ max_rows_per_request: int = pydantic.Field(+ default=1000,+ description=f"Most dependent rows one personhog request may delete, between {STEP_FLOOR_ROWS} and "+ f"{REPLICA_MAX_ROWS}. Requests start at {STEP_START_ROWS} rows and grow toward this after runs of "+ "successes; a timeout halves the step. 1000 rows is the largest step that fits the router's 5 s "+ "deadline at the measured tail cost per row.",+ )+ pause_ms: int = pydantic.Field(default=200, description="Pause after every personhog request.")+ latency_multiplier: float = pydantic.Field(+ default=1.0,+ description="Extra pause after every request, as a multiple of that request's latency. When the persons "+ "writer slows down, the drain slows down with it.",+ )+ rpc_timeout_seconds: float = pydantic.Field(+ default=ROUTER_BACKEND_TIMEOUT_SECONDS,+ description="Deadline per personhog request. personhog-router caps every backend call at 5 s and re-sends "+ "a timed-out call, so a longer deadline only lets one slow step run several times.",+ )+ max_runtime_seconds: int = pydantic.Field(+ default=24 * 3600,+ description="Stop taking new pages and requests after this many seconds, then finish cleanly; 0 means no "+ "cap. Rows left over wait for the next run; rows already deleted stay deleted.",+ )+ retry_backoff_seconds: float = pydantic.Field(+ default=2.0,+ description="Pause before the retry of a failed personhog request. Doubles per consecutive failure, capped "+ "at 60 s.",+ )+ rpc_retry_window_seconds: float = pydantic.Field(+ default=3600.0,+ description="Keep retrying one failing personhog request for this long before the run fails. Long enough "+ "to ride out a replica rollout, a database failover or a cold buffer cache; a run that fails here found "+ "personhog down.",+ )+ pg_retry_window_seconds: float = pydantic.Field(+ default=1800.0,+ description="Keep retrying one failing queue statement for this long, reconnecting after a lost connection, "+ "before the run fails.",+ )+ blocked_retry_hours: int = pydantic.Field(+ default=24, description="Skip rows stamped blocked_at more recently than this."+ )+ max_blocked: int = pydantic.Field(+ default=1000,+ description="Fail the run once more rows than this are stamped blocked_at in one run: tombstoned persons "+ "that still own a live distinct id. That many needs a person, not a retry.",+ )++ @pydantic.model_validator(mode="after")+ def validate_bounds(self) -> "DrainConfig":+ if not 1 <= self.page_size <= RPC_MAX_UUIDS:+ raise ValueError(f"page_size must be between 1 and {RPC_MAX_UUIDS}")+ if not 1 <= self.rpc_batch_size <= RPC_MAX_UUIDS:+ raise ValueError(f"rpc_batch_size must be between 1 and {RPC_MAX_UUIDS}")+ if not STEP_FLOOR_ROWS <= self.max_rows_per_request <= REPLICA_MAX_ROWS:+ raise ValueError(f"max_rows_per_request must be between {STEP_FLOOR_ROWS} and {REPLICA_MAX_ROWS}")+ if self.rpc_timeout_seconds <= 0:+ raise ValueError("rpc_timeout_seconds must be positive")+ if min(self.max_persons, self.max_runtime_seconds, self.pause_ms, self.latency_multiplier) < 0:+ raise ValueError("max_persons, max_runtime_seconds, pause_ms and latency_multiplier must not be negative")+ if self.blocked_retry_hours < 0:+ raise ValueError("blocked_retry_hours must not be negative")+ if (+ min(+ self.retry_backoff_seconds,+ self.rpc_retry_window_seconds,+ self.pg_retry_window_seconds,+ self.max_blocked,+ )+ < 0+ ):+ raise ValueError(+ "retry_backoff_seconds, rpc_retry_window_seconds, pg_retry_window_seconds and max_blocked must not "+ "be negative"+ )+ return self+++@frozen+class QueueRow:+ team_id: int+ person_uuid: str+ deleted_at: datetime+++@frozen+class QueueCursor:+ team_id: int+ person_uuid: str+++@frozen+class Chunk:+ """One personhog request: persons of one team, queued by one sweep run."""++ team_id: int+ deleted_at: datetime+ person_uuids: tuple[str, ...]+++@frozen(frozen=False)+class DrainTotals:+ dry_run: bool = False+ rows_read: int = 0+ pages: int = 0+ chunks: int = 0+ rpc_calls: int = 0+ rpc_errors: int = 0+ requests_pending_resent: int = 0+ persons_deleted: int = 0+ persons_skipped_live: int = 0+ persons_not_found: int = 0+ persons_blocked: int = 0+ rows_deleted: int = 0+ rows_stamped_blocked: int = 0+ blocked_sample: list[str] = field(default_factory=list)+ queue_rows_deleted: int = 0+ step_rows_min: int = 0+ step_rows_max: int = 0+ pg_reconnects: int = 0+ rpc_seconds_total: float = 0.0+ rpc_seconds_max: float = 0.0+ rpc_seconds_last: float = 0.0+ pg_seconds_total: float = 0.0+ teams_touched: set[int] = field(default_factory=set)+ queue_rows_estimate_at_start: int = 0+ stopped_reason: str = "drained"++ def rpc_seconds_mean(self) -> float:+ return self.rpc_seconds_total / self.rpc_calls if self.rpc_calls else 0.0++ def as_metadata(self) -> dict[str, dagster.MetadataValue]:+ return {+ "rows_read": dagster.MetadataValue.int(self.rows_read),+ "pages": dagster.MetadataValue.int(self.pages),+ "chunks": dagster.MetadataValue.int(self.chunks),+ "rpc_calls": dagster.MetadataValue.int(self.rpc_calls),+ "rpc_errors": dagster.MetadataValue.int(self.rpc_errors),+ "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_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),+ "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),+ "step_rows_max": dagster.MetadataValue.int(self.step_rows_max),+ "pg_reconnects": dagster.MetadataValue.int(self.pg_reconnects),+ "rpc_seconds_total": dagster.MetadataValue.float(round(self.rpc_seconds_total, 3)),+ "rpc_seconds_max": dagster.MetadataValue.float(round(self.rpc_seconds_max, 3)),+ "rpc_seconds_mean": dagster.MetadataValue.float(round(self.rpc_seconds_mean(), 3)),+ "pg_seconds_total": dagster.MetadataValue.float(round(float(self.pg_seconds_total), 3)),+ "teams_touched": dagster.MetadataValue.int(len(self.teams_touched)),+ "queue_rows_estimate_at_start": dagster.MetadataValue.int(self.queue_rows_estimate_at_start),+ "stopped_reason": dagster.MetadataValue.text(self.stopped_reason),+ }+++class _OutOfTime(Exception):+ """The run's deadline passed while a request or statement was being retried."""+++def chunks_for_page(rows: Sequence[QueueRow], rpc_batch_size: int) -> list[Chunk]:+ """Group a page into personhog requests: one team and one sweep run per request.++ 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.+ """+ grouped: dict[tuple[int, datetime], list[str]] = defaultdict(list)+ 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)+ ]+++PgRecovery = Literal["retry", "reconnect"]+++def pg_recovery(exc: BaseException) -> PgRecovery | None:+ """How a failed queue statement can be run again, or None when it cannot."""+ if not isinstance(exc, psycopg2.Error):+ return None+ # Serialization failure, deadlock, lock_timeout and statement_timeout: the same connection+ # can simply run the statement again.+ if getattr(exc, "pgcode", None) in {"40001", "40P01", "55P03", "57014"}:+ return "retry"+ # psycopg2 raises OperationalError for a dropped or refused connection and InterfaceError for+ # a connection already closed; both need a new connection first.+ if isinstance(exc, psycopg2.OperationalError | psycopg2.InterfaceError):+ return "reconnect"+ return None+++def pause_seconds(pause_ms: int, latency_multiplier: float, last_rpc_seconds: float) -> float:+ return pause_ms / 1000.0 + latency_multiplier * last_rpc_seconds+++def backoff_seconds(base: float, failures: int) -> float:+ return min(base * 2 ** (failures - 1), RETRY_BACKOFF_CAP_SECONDS)+++def _status_code(exc: grpc.RpcError) -> grpc.StatusCode | None:+ code = getattr(exc, "code", None)+ return code() if callable(code) else None+++def _code_name(code: grpc.StatusCode | None) -> str:+ return code.name if code else "unknown"+++def _now_monotonic() -> float:+ return time.monotonic()+++def _pause(seconds: float) -> None:+ if seconds > 0:+ time.sleep(seconds)+++def _emit(metrics: MetricsClient, name: str, labels: Mapping[str, str], value: float = 1.0) -> None:+ """Record a counter, never letting telemetry fail the drain."""+ if value <= 0:+ return+ try:+ metrics.increment(name, labels=dict(labels), value=value).result()+ except Exception:+ logger.warning("failed to record %s", name, exc_info=True)+++def _connect(persons_database_url: str) -> psycopg2.extensions.connection:+ # Autocommit: one statement per transaction, so no transaction stays open on the persons+ # writer across a personhog call or a pause.+ connection = psycopg2.connect(persons_database_url, connect_timeout=10)+ connection.autocommit = True+ with connection.cursor() as cursor:+ cursor.execute("SET application_name = %s", (PG_APPLICATION_NAME,))+ cursor.execute("SET statement_timeout = '30s'")+ cursor.execute("SET lock_timeout = '5s'")+ return connection+++def _read_page(+ cursor: psycopg2.extensions.cursor,+ after: QueueCursor | None,+ limit: int,+ blocked_before: datetime,+) -> list[QueueRow]:+ # Keyset over the primary key. Drained rows are gone, so the walk never revisits them, and+ # the cursor carries the run past rows it left in place (blocked ones).+ 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+ FROM {PG_CLEANUP_QUEUE_TABLE}+ WHERE (blocked_at IS NULL OR blocked_at < %(blocked_before)s)+ {cursor_filter}+ ORDER BY team_id, person_uuid+ LIMIT %(limit)s+ """,+ {+ "after_team": after.team_id if after else 0,+ "after_uuid": after.person_uuid if after else "00000000-0000-0000-0000-000000000000",+ "blocked_before": blocked_before,+ "limit": limit,+ },+ )+ 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()+ ]+++def _delete_queue_rows(cursor: psycopg2.extensions.cursor, chunk: Chunk, person_uuids: Sequence[str]) -> int:+ if not person_uuids:+ return 0+ # The deleted_at guard leaves a row the sweep re-queued (new deleted_at) between our read and+ # this delete; that person is drained again on the strength of the newer tombstone.+ cursor.execute(+ f"""+ DELETE FROM {PG_CLEANUP_QUEUE_TABLE}+ WHERE team_id = %s AND deleted_at = %s AND person_uuid = ANY(%s::uuid[])+ """,+ (chunk.team_id, chunk.deleted_at, list(person_uuids)),+ )+ return cursor.rowcount+++def _mark_blocked(cursor: psycopg2.extensions.cursor, chunk: Chunk, person_uuids: Sequence[str]) -> list[str]:+ """Stamp the rows and return the uuids actually stamped."""+ if not person_uuids:+ return []+ # Same deleted_at guard as the delete: a row the sweep re-queued mid-flight belongs to a newer+ # tombstone, and stamping it blocked on this stale answer would park it for the retry window.+ cursor.execute(+ f"""+ UPDATE {PG_CLEANUP_QUEUE_TABLE}+ SET blocked_at = now()+ WHERE team_id = %s AND deleted_at = %s AND person_uuid = ANY(%s::uuid[])+ RETURNING person_uuid+ """,+ (chunk.team_id, chunk.deleted_at, list(person_uuids)),+ )+ return [str(person_uuid) for (person_uuid,) in cursor.fetchall()]+++def _queue_rows_estimate(cursor: psycopg2.extensions.cursor) -> int:+ # Planner statistics, so this is free however large the queue grows; an exact count would+ # scan every pending row.+ cursor.execute("SELECT reltuples::bigint FROM pg_class WHERE oid = %s::regclass", (PG_CLEANUP_QUEUE_TABLE,))+ [[estimate]] = cursor.fetchall()+ return max(int(estimate), 0)+++def _personhog_client() -> PersonHogClient:+ try:+ return require_personhog_client()+ except RuntimeError as exc:+ raise dagster.Failure(+ "personhog client is not configured: PERSONHOG_ADDR is unset in this pod, so the drain cannot delete"+ ) from exc+++def _request_metadata(chunk: Chunk, sent: Sequence[str]) -> dict[str, dagster.MetadataValue]:+ return {+ "team_id": dagster.MetadataValue.int(chunk.team_id),+ "deleted_at": dagster.MetadataValue.text(chunk.deleted_at.isoformat()),+ "chunk_size": dagster.MetadataValue.int(len(chunk.person_uuids)),+ "sent_size": dagster.MetadataValue.int(len(sent)),+ "first_uuid": dagster.MetadataValue.text(sent[0]),+ "last_uuid": dagster.MetadataValue.text(sent[-1]),+ }+++class _Drain:+ """One run's state: the personhog client, the Postgres session, the step size and the totals."""++ def __init__(+ self,+ context: dagster.OpExecutionContext,+ config: DrainConfig,+ metrics: MetricsClient,+ client: PersonHogClient | None,+ persons_database_url: str,+ ) -> None:+ self.context = context+ self.config = config+ self.metrics = metrics+ self.client = client+ self.persons_database_url = persons_database_url+ self.connection: psycopg2.extensions.connection | None = None+ self.totals = DrainTotals(dry_run=config.dry_run)+ self.step_rows = min(STEP_START_ROWS, config.max_rows_per_request)+ self.totals.step_rows_min = self.totals.step_rows_max = self.step_rows+ self.successes_at_step = 0+ self.deadline = math.inf if config.max_runtime_seconds == 0 else _now_monotonic() + config.max_runtime_seconds+ self.blocked_before = datetime.now(UTC) - timedelta(hours=config.blocked_retry_hours)++ def out_of_time(self) -> bool:+ if _now_monotonic() <= self.deadline:+ return False+ self.totals.stopped_reason = "max_runtime"+ return True++ def page_limit(self) -> int:+ if self.config.max_persons == 0:+ return self.config.page_size+ return min(self.config.page_size, self.config.max_persons - self.totals.rows_read)++ def close(self) -> None:+ if self.connection is None:+ return+ try:+ self.connection.close()+ except Exception:+ self.context.log.warning("closing the persons connection failed", exc_info=True)+ self.connection = None++ def timed_pg(self, fn: Callable[[psycopg2.extensions.cursor], _T]) -> _T:+ """Run one queue statement, retrying conflicts and reconnecting after a lost connection.++ Every statement is idempotent (a keyset read, a guarded delete, a guarded stamp), so running+ it again after a failure of unknown outcome is safe.+ """+ spent = 0.0+ failures = 0+ while True:+ started = time.perf_counter()+ try:+ if self.connection is None:+ self.connection = _connect(self.persons_database_url)+ if failures:+ self.totals.pg_reconnects += 1+ with self.connection.cursor() as cursor:+ result = fn(cursor)+ except psycopg2.Error as exc:+ elapsed = time.perf_counter() - started+ spent += elapsed+ self.totals.pg_seconds_total += elapsed+ failures += 1+ recovery = pg_recovery(exc)+ if recovery is None:+ raise dagster.Failure(+ f"persons Postgres statement failed: {exc}", metadata=self.totals.as_metadata()+ ) from exc+ if spent >= self.config.pg_retry_window_seconds:+ raise dagster.Failure(+ f"persons Postgres kept failing for {spent:.0f}s over {failures} attempts: {exc}",+ metadata=self.totals.as_metadata(),+ ) from exc+ if recovery == "reconnect":+ self.close()+ if self.out_of_time():+ raise _OutOfTime from exc+ pause = backoff_seconds(PG_RETRY_BACKOFF_SECONDS, failures)+ self.context.log.warning(+ "persons Postgres %s (%s); attempt %d in %.1fs",+ "connection lost, reconnecting" if recovery == "reconnect" else "statement conflicted, retrying",+ getattr(exc, "pgcode", None) or type(exc).__name__,+ failures + 1,+ pause,+ )+ _pause(pause)+ spent += pause+ continue+ self.totals.pg_seconds_total += time.perf_counter() - started+ return result++ def pages(self) -> Iterator[list[QueueRow]]:+ after: QueueCursor | None = None+ while not self.out_of_time():+ limit = self.page_limit()+ if limit <= 0:+ self.totals.stopped_reason = "max_persons"+ return+ read = partial(_read_page, after=after, limit=limit, blocked_before=self.blocked_before)+ page = self.timed_pg(read)+ if not page:+ return+ self.totals.rows_read += len(page)+ self.totals.pages += 1+ self.totals.teams_touched.update(row.team_id for row in page)+ yield page+ last = page[-1]+ after = QueueCursor(team_id=last.team_id, person_uuid=last.person_uuid)++ def send(self, chunk: Chunk, uuids: Sequence[str]) -> DeleteTombstonedPersonsResponse:+ """One personhog request, retried with backoff until it succeeds or the retry window passes.++ A timeout halves the row budget before the retry, so a step that outran the router's+ deadline is re-sent smaller; nothing is ever stamped or skipped because of a failed request.+ """+ assert self.client is not None+ client = self.client+ request = DeleteTombstonedPersonsRequest(team_id=chunk.team_id, person_uuids=list(uuids))+ spent = 0.0+ failures = 0+ while True:+ request.max_rows = self.step_rows+ started = time.perf_counter()+ try:+ response = personhog_call(+ "delete_tombstoned_persons",+ lambda: client.delete_tombstoned_persons(request, timeout=self.config.rpc_timeout_seconds),+ caller_tag=PERSONHOG_CALLER_TAG,+ )+ except grpc.RpcError as exc:+ spent += time.perf_counter() - started+ code = _status_code(exc)+ failures += 1+ self.totals.rpc_errors += 1+ _emit(self.metrics, "person_pg_cleanup_drain_rpc_calls", {"result": "error", "code": _code_name(code)})+ if code == grpc.StatusCode.UNIMPLEMENTED:+ # An older router or replica does not know the RPC. Failing here is the point:+ # the legacy DeletePersons would hard-delete revived persons.+ raise dagster.Failure(+ "personhog does not serve DeleteTombstonedPersons yet; deploy personhog-router and "+ "personhog-replica with it before running the drain",+ metadata={**self.totals.as_metadata(), **_request_metadata(chunk, uuids)},+ ) from exc+ if code in FATAL_RPC_CODES:+ raise dagster.Failure(+ f"personhog rejected the request with {_code_name(code)}; retrying cannot change that",+ metadata={**self.totals.as_metadata(), **_request_metadata(chunk, uuids)},+ ) from exc+ if code in SLOW_RPC_CODES:+ self.shrink_step()+ if spent >= self.config.rpc_retry_window_seconds:+ raise dagster.Failure(+ f"personhog kept failing for {spent:.0f}s over {failures} attempts (last {_code_name(code)}); "+ "the rows of this request stay queued for the next run",+ metadata={+ **self.totals.as_metadata(),+ **_request_metadata(chunk, uuids),+ "attempts": dagster.MetadataValue.int(failures),+ "grpc_code": dagster.MetadataValue.text(_code_name(code)),+ },+ ) from exc+ if self.out_of_time():+ raise _OutOfTime from exc+ pause = backoff_seconds(self.config.retry_backoff_seconds, failures)+ self.context.log.warning(+ "personhog delete of %d persons failed (%s); attempt %d in %.1fs with a %d-row budget",+ len(uuids),+ _code_name(code),+ failures + 1,+ pause,+ self.step_rows,+ )+ _pause(pause)+ spent += pause+ continue+ elapsed = time.perf_counter() - started+ self.totals.rpc_calls += 1+ self.totals.rpc_seconds_total += elapsed+ self.totals.rpc_seconds_max = max(self.totals.rpc_seconds_max, elapsed)+ self.totals.rpc_seconds_last = elapsed+ self.grow_step()+ return response++ def shrink_step(self) -> None:+ self.step_rows = max(STEP_FLOOR_ROWS, self.step_rows // 2)+ self.successes_at_step = 0+ self.totals.step_rows_min = min(self.totals.step_rows_min, self.step_rows)++ def grow_step(self) -> None:+ self.successes_at_step += 1+ if self.successes_at_step < STEP_GROWTH_SUCCESSES:+ return+ self.step_rows = min(self.step_rows * 2, self.config.max_rows_per_request)+ self.successes_at_step = 0+ self.totals.step_rows_max = max(self.totals.step_rows_max, self.step_rows)++ def resolve(self, chunk: Chunk) -> None:+ """Send the chunk, then send its pending persons again until personhog has resolved every one."""+ self.totals.chunks += 1+ pending: Sequence[str] = chunk.person_uuids+ while pending:+ if self.out_of_time():+ # Rows of the persons still pending stay queued; the next run continues them.+ return+ response = self.send(chunk, pending)+ self.apply(chunk, pending, response)+ _pause(pause_seconds(self.config.pause_ms, self.config.latency_multiplier, self.totals.rpc_seconds_last))+ pending = list(response.pending_person_uuids)+ if pending:+ self.totals.requests_pending_resent += 1++ def apply(self, chunk: Chunk, sent: Sequence[str], response: DeleteTombstonedPersonsResponse) -> None:+ blocked = sorted(response.blocked_person_uuids)+ 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.+ 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_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))+ if blocked:+ self.stamp_blocked(chunk, blocked)++ def stamp_blocked(self, chunk: Chunk, uuids: Sequence[str]) -> None:+ stamped = self.timed_pg(lambda cursor: _mark_blocked(cursor, chunk, list(uuids)))+ self.totals.rows_stamped_blocked += len(stamped)+ room = max(0, BLOCKED_SAMPLE_SIZE - len(self.totals.blocked_sample))+ self.totals.blocked_sample.extend(stamped[:room])+ if self.totals.rows_stamped_blocked <= self.config.max_blocked:+ return+ raise dagster.Failure(+ f"{self.totals.rows_stamped_blocked} queue rows stamped blocked_at this run (tombstoned persons that "+ f"still own a live distinct id), more than max_blocked={self.config.max_blocked}; this needs "+ "investigation, not more retries",+ metadata={**self.totals.as_metadata(), **_request_metadata(chunk, uuids)},+ )++ def emit_counters_since(self, before: DrainTotals) -> None:+ after = self.totals+ for outcome, delta in (+ ("deleted", after.persons_deleted - before.persons_deleted),+ ("skipped_live", after.persons_skipped_live - before.persons_skipped_live),+ ("not_found", after.persons_not_found - before.persons_not_found),+ ("blocked", after.persons_blocked - before.persons_blocked),+ ):+ _emit(self.metrics, "person_pg_cleanup_drain_persons", {"outcome": outcome}, delta)+ _emit(self.metrics, "person_pg_cleanup_drain_rows_deleted", {}, after.rows_deleted - before.rows_deleted)+ _emit(+ self.metrics,+ "person_pg_cleanup_drain_queue_rows_deleted",+ {},+ after.queue_rows_deleted - before.queue_rows_deleted,+ )+ _emit(+ self.metrics,+ "person_pg_cleanup_drain_rpc_calls",+ {"result": "ok", "code": "OK"},+ after.rpc_calls - before.rpc_calls,+ )+ _emit(self.metrics, "person_pg_cleanup_drain_pg_reconnects", {}, after.pg_reconnects - before.pg_reconnects)++ def snapshot(self) -> DrainTotals:+ return DrainTotals(+ persons_deleted=self.totals.persons_deleted,+ persons_skipped_live=self.totals.persons_skipped_live,+ persons_not_found=self.totals.persons_not_found,+ persons_blocked=self.totals.persons_blocked,+ rows_deleted=self.totals.rows_deleted,+ queue_rows_deleted=self.totals.queue_rows_deleted,+ rpc_calls=self.totals.rpc_calls,+ pg_reconnects=self.totals.pg_reconnects,+ )++ def run(self) -> DrainTotals:+ self.totals.queue_rows_estimate_at_start = self.timed_pg(_queue_rows_estimate)+ # Counters flush every LOG_EVERY_PAGES pages and once on the way out, success or failure:+ # per-page inserts would be tens of thousands of tiny ClickHouse inserts on a large queue.+ emitted = self.snapshot()+ try:+ for page in self.pages():+ if self.config.dry_run:+ continue+ for chunk in chunks_for_page(page, self.config.rpc_batch_size):+ self.resolve(chunk)+ if self.totals.stopped_reason == "max_runtime":+ break+ if self.totals.pages % LOG_EVERY_PAGES == 0:+ self.emit_counters_since(emitted)+ emitted = self.snapshot()+ self.log_progress()+ if self.totals.stopped_reason == "max_runtime":+ # Requests left in this page were never sent, so their rows stay queued.+ break+ except _OutOfTime:+ # Raised inside a retry, so the rows of that request stay queued for the next run.+ pass+ except Exception:+ self.totals.stopped_reason = "failed"+ raise+ finally:+ self.emit_counters_since(emitted)+ return self.totals++ 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",+ totals.pages,+ totals.rows_read,+ totals.persons_deleted,+ totals.persons_skipped_live,+ totals.persons_not_found,+ totals.persons_blocked,+ totals.rows_deleted,+ totals.requests_pending_resent,+ self.step_rows,+ totals.step_rows_min,+ totals.step_rows_max,+ totals.rpc_seconds_mean(),+ totals.rpc_errors,+ totals.pg_reconnects,+ )+++def drain_person_pg_cleanup_queue(+ context: dagster.OpExecutionContext,+ config: DrainConfig,+ cluster: dagster.ResourceParam[ClickhouseCluster],+ persons_database_url: dagster.ResourceParam[str],+) -> DrainTotals:+ """Page the queue by primary key, delete each batch through personhog, remove the resolved rows.++ A dry run pages and counts only: it never resolves the personhog client and never writes.+ """+ # Resolved before Postgres is dialed, so a pod without PERSONHOG_ADDR fails before it+ # touches the persons writer.+ client = None if config.dry_run else _personhog_client()++ metrics = MetricsClient(cluster)+ drain = _Drain(context, config, metrics, client, persons_database_url)+ try:+ totals = drain.run()+ finally:+ drain.close()+ drain.log_progress()+ _emit(+ metrics,+ "person_pg_cleanup_drain_runs",+ {"stopped_reason": drain.totals.stopped_reason, "dry_run": str(config.dry_run).lower()},+ )++ context.add_output_metadata({**totals.as_metadata(), "dry_run": dagster.MetadataValue.bool(config.dry_run)})+ return totals+++def _drain_gauges(totals: DrainTotals, completed_at: float) -> list[PublishedGauge]:+ prefix = "posthog_person_pg_cleanup_drain_"+ return [+ PublishedGauge(+ name=f"{prefix}last_success_timestamp_seconds",+ help_text="Unix time when the drain last finished a live run",+ value=completed_at,+ ),+ PublishedGauge(+ name=f"{prefix}queue_rows_estimate_at_start",+ help_text="Queue rows the planner estimated when the run started",+ value=totals.queue_rows_estimate_at_start,+ ),+ PublishedGauge(name=f"{prefix}rows_read", help_text="Queue rows the run read", value=totals.rows_read),+ PublishedGauge(+ name=f"{prefix}persons_deleted", help_text="Persons the run hard-deleted", value=totals.persons_deleted+ ),+ PublishedGauge(+ name=f"{prefix}persons_blocked",+ help_text="Tombstoned persons personhog reported as still owning a live distinct id",+ value=totals.persons_blocked,+ ),+ PublishedGauge(+ name=f"{prefix}rows_deleted", help_text="Dependent rows the run deleted", value=totals.rows_deleted+ ),+ PublishedGauge(+ name=f"{prefix}rows_stamped_blocked",+ help_text="Queue rows the run stamped blocked_at",+ value=totals.rows_stamped_blocked,+ ),+ PublishedGauge(+ name=f"{prefix}requests_pending_resent",+ help_text="Requests sent again for persons personhog returned as pending",+ value=totals.requests_pending_resent,+ ),+ PublishedGauge(+ name=f"{prefix}step_rows_min",+ help_text="Smallest row budget a request used; it halves after timeouts",+ value=totals.step_rows_min,+ ),+ PublishedGauge(+ name=f"{prefix}rpc_errors", help_text="Failed personhog attempts, all retried", value=totals.rpc_errors+ ),+ PublishedGauge(+ name=f"{prefix}pg_reconnects",+ help_text="Times the persons Postgres connection was reopened",+ value=totals.pg_reconnects,+ ),+ PublishedGauge(+ name=f"{prefix}rpc_seconds_max",+ help_text="Slowest successful personhog request",+ value=totals.rpc_seconds_max,+ ),+ ]+++def publish_drain_metrics(context: dagster.OpExecutionContext, totals: DrainTotals) -> DrainTotals:+ """Publish what the run measured, so alerting and dashboards can read it.++ A dry run publishes nothing. It deletes nothing, so moving the last-success gauge would let an+ ad-hoc run from the Dagster UI mask a drain that has stopped working.+ """+ if totals.dry_run:+ context.log.info("dry run: publishing no metrics")+ return totals++ gauges = _drain_gauges(totals, time.time())+ with pushed_metrics_registry(DRAIN_METRICS_JOB) as registry:+ for gauge in gauges:+ Gauge(gauge.name, gauge.help_text, registry=registry).set(gauge.value)++ context.add_output_metadata({gauge.name: dagster.MetadataValue.float(gauge.value) for gauge in gauges})+ return totals+++ tags={+ "owner": JobOwners.TEAM_INGESTION.value,+ # The sweep's run-queue tag (limit 1 in charts argocd/dagster/deployment_settings), so a+ # drain never runs alongside a sweep or another drain.+ "clickhouse_deletion_sweep_concurrency": "v1",+ },+ executor_def=dagster.in_process_executor,+)+def person_pg_cleanup_drain_job():+ """Hard-delete the Postgres rows of persons the ClickHouse sweep has already removed."""+ publish_drain_metrics(drain_person_pg_cleanup_queue())diff --git a/posthog/dags/tests/conftest.py b/posthog/dags/tests/conftest.pyindex 5acbe732bb67..b2ceaf7693e9 100644--- a/posthog/dags/tests/conftest.py+++ b/posthog/dags/tests/conftest.py@@ -12,10 +12,13 @@ from unittest.mock import patchfrom django.conf import settings+import psycopg2+import psycopg2.extensionsfrom clickhouse_driver import Clientfrom psycopg.types.json import Jsonbfrom posthog.clickhouse.cluster import ClickhouseCluster, get_cluster+from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE# Import the shared Dagster PostgreSQL fixtures so they apply to all tests# in this directory. Direct import (rather than pytest_plugins) is required@@ -24,7 +27,7 @@ from posthog.dags.tests.dagster_pg_fixtures import ( # noqa: F401_dagster_postgres_instance,_use_postgres_dagster_instance,)-from posthog.persons_db import persons_db_connection+from posthog.persons_db import persons_db_connection, persons_db_urldef insert_flag_evaluations(rows: list[tuple], client: Client) -> None:@@ -118,3 +121,16 @@ def isolated_clickhouse_cluster() -> Iterator[ClickhouseCluster]:def cluster(django_db_setup) -> Iterator[ClickhouseCluster]:with isolated_clickhouse_cluster() as clickhouse_cluster:yield clickhouse_cluster+++def persons_database() -> Iterator[psycopg2.extensions.connection]:+ """A writer connection to the test persons DB with the cleanup queue emptied."""+ conn = psycopg2.connect(persons_db_url(writer=True))+ try:+ with conn.cursor() as cursor:+ cursor.execute(f"TRUNCATE {PG_CLEANUP_QUEUE_TABLE}")+ conn.commit()+ yield conn+ finally:+ conn.close()diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.pyindex 7dc4d0f5926a..4184fea6b10a 100644--- a/posthog/dags/tests/test_clickhouse_cleanup.py+++ b/posthog/dags/tests/test_clickhouse_cleanup.py@@ -46,18 +46,6 @@ COHORT_ID = 77RUN_FOR_REAL = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False}}}}-def persons_database() -> Iterator[psycopg2.extensions.connection]:- conn = psycopg2.connect(persons_db_url(writer=True))- try:- with conn.cursor() as cursor:- cursor.execute(f"TRUNCATE {PG_CLEANUP_QUEUE_TABLE}")- conn.commit()- yield conn- finally:- conn.close()--def run_job(cluster: ClickhouseCluster, persons_database, run_config=RUN_FOR_REAL, raise_on_error=True, instance=None):return clickhouse_deletion_sweep_job.execute_in_process(run_config=run_config,diff --git a/posthog/dags/tests/test_person_pg_cleanup_drain.py b/posthog/dags/tests/test_person_pg_cleanup_drain.pynew file mode 100644index 000000000000..50cd6925a762--- /dev/null+++ b/posthog/dags/tests/test_person_pg_cleanup_drain.py@@ -0,0 +1,842 @@+import time+import itertools+from collections.abc import Iterator, Mapping+from contextlib import AbstractContextManager, contextmanager+from datetime import UTC, datetime+from functools import partial+from uuid import uuid4++import pytest+from unittest.mock import patch++import grpc+import dagster+import psycopg2+from prometheus_client import CollectorRegistry++from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.custom_metrics import MetricsClient+from posthog.dags import person_pg_cleanup_drain as drain+from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE+from posthog.dags.person_pg_cleanup_drain import (+ Chunk,+ DrainTotals,+ QueueRow,+ backoff_seconds,+ chunks_for_page,+ person_pg_cleanup_drain_job,+ pg_recovery,+)+from posthog.personhog_client.fake_client import FakePersonHogClient, get_active_fake+from posthog.personhog_client.proto import (+ DeleteTombstonedPersonsRequest,+ DeleteTombstonedPersonsResponse,+ GetPersonByUuidRequest,+)+from posthog.persons_db import persons_db_url++TEAM_A = 4242+TEAM_B = 4343+# Sweep timestamps are only ever compared with each other, never with the clock.+SWEEP_1 = datetime(2026, 1, 1, tzinfo=UTC)+SWEEP_2 = datetime(2026, 1, 8, tzinfo=UTC)+OP = "drain_person_pg_cleanup_queue"++# Pacing and backoff are zeroed so the suite never sleeps.+FAST = {"pause_ms": 0, "latency_multiplier": 0.0, "retry_backoff_seconds": 0.0}+++def queue(conn, rows: list[tuple[int, str, datetime]]) -> 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+ )+ conn.commit()+++def queued(conn) -> list[tuple[int, str, datetime, datetime | None]]:+ with conn.cursor() as cursor:+ cursor.execute(+ f"SELECT team_id, person_uuid::text, deleted_at, blocked_at FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 1, 2"+ )+ return cursor.fetchall()+++def run_job(cluster: ClickhouseCluster, *, dry_run: bool = False, raise_on_error: bool = True, **overrides):+ config = {"dry_run": dry_run, **FAST, **overrides}+ return person_pg_cleanup_drain_job.execute_in_process(+ run_config={"ops": {OP: {"config": config}}},+ resources={"cluster": cluster, "persons_database_url": persons_db_url(writer=True)},+ raise_on_error=raise_on_error,+ )+++def totals_of(result: dagster.ExecuteInProcessResult) -> DrainTotals:+ return result.output_for_node(OP)+++def failure_of(result: dagster.ExecuteInProcessResult) -> tuple[str, Mapping[str, dagster.MetadataValue]]:+ failure = result.failure_data_for_node(OP)+ assert failure is not None and failure.user_failure_data is not None+ return failure.user_failure_data.description or "", failure.user_failure_data.metadata+++def seed_tombstoned(fake: FakePersonHogClient, team_id: int, person_id: int) -> 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,+ distinct_ids=distinct_ids,+ is_deleted=True,+ tombstoned_distinct_ids=distinct_ids,+ )+ return uuid+++def seed_live(fake: FakePersonHogClient, team_id: int, person_id: int) -> str:+ uuid = str(uuid4())+ fake.add_person(team_id=team_id, person_id=person_id, uuid=uuid, distinct_ids=[f"{person_id}-a"])+ return uuid+++def seed_blocked(fake: FakePersonHogClient, team_id: int, person_id: int) -> str:+ uuid = str(uuid4())+ fake.add_person(+ team_id=team_id,+ person_id=person_id,+ uuid=uuid,+ distinct_ids=[f"{person_id}-a", f"{person_id}-live"],+ is_deleted=True,+ tombstoned_distinct_ids=[f"{person_id}-a"],+ )+ return uuid+++def seed_big(fake: FakePersonHogClient, team_id: int, person_id: int, distinct_ids: int = 5, live: int = 0) -> str:+ # Over the fake's row budget of two per request, which stands in for the replica's+ # TOMBSTONED_DELETE_MAX_ROWS clamp; the first `live` distinct ids stay live.+ uuid = str(uuid4())+ fake.tombstoned_delete_max_rows = 2+ ids = [f"{person_id}-{i}" for i in range(distinct_ids)]+ fake.add_person(+ team_id=team_id,+ person_id=person_id,+ uuid=uuid,+ distinct_ids=ids,+ is_deleted=True,+ tombstoned_distinct_ids=ids[live:],+ )+ return uuid+++def present(fake: FakePersonHogClient, team_id: int, uuid: str) -> bool:+ return fake.get_person_by_uuid(GetPersonByUuidRequest(team_id=team_id, uuid=uuid)).HasField("person")+++def delete_requests(fake: FakePersonHogClient) -> list:+ return [call.request for call in fake.calls if call.method == "delete_tombstoned_persons"]+++def distinct_id_count(fake: FakePersonHogClient, team_id: int, uuid: str) -> int:+ person = fake.get_person_by_uuid(GetPersonByUuidRequest(team_id=team_id, uuid=uuid)).person+ return len(fake._distinct_ids.get((team_id, person.id), []))+++class _RpcError(grpc.RpcError):+ def __init__(self, code: grpc.StatusCode) -> None:+ super().__init__()+ self._code = code++ def code(self) -> grpc.StatusCode:+ return self._code+++def fail_with(monkeypatch: pytest.MonkeyPatch, fake: FakePersonHogClient, codes: list[grpc.StatusCode]) -> None:+ # The first len(codes) requests raise the given status before reaching the fake; later ones+ # reach it.+ pending = list(codes)+ original = fake.delete_tombstoned_persons++ def wrapped(+ request: DeleteTombstonedPersonsRequest, timeout: float | None = None+ ) -> DeleteTombstonedPersonsResponse:+ if pending:+ raise _RpcError(pending.pop(0))+ return original(request, timeout=timeout)++ monkeypatch.setattr(fake, "delete_tombstoned_persons", wrapped)+++def record_emits(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, str]]]:+ emitted: list[tuple[str, dict[str, str]]] = []++ def recorder(metrics: MetricsClient, name: str, labels: Mapping[str, str], value: float = 1.0) -> None:+ emitted.append((name, dict(labels)))++ monkeypatch.setattr(drain, "_emit", recorder)+ return emitted+++def record_pauses(monkeypatch: pytest.MonkeyPatch) -> list[float]:+ pauses: list[float] = []+ monkeypatch.setattr(drain, "_pause", pauses.append)+ return pauses+++def _pg_error(pgcode: str | None) -> psycopg2.Error:+ # pgcode is a read-only attribute on psycopg2.Error, so a subclass attribute stands in for it.+ return type("_PgError", (psycopg2.Error,), {"pgcode": pgcode})()+++def test_deletes_tombstoned_persons_and_removes_their_queue_rows(cluster: ClickhouseCluster, persons_database):+ fake = get_active_fake()+ a1 = seed_tombstoned(fake, TEAM_A, 1)+ a2 = seed_tombstoned(fake, TEAM_A, 2)+ b1 = seed_tombstoned(fake, TEAM_B, 3)+ queue(persons_database, [(TEAM_A, a1, SWEEP_1), (TEAM_A, a2, SWEEP_1), (TEAM_B, b1, SWEEP_1)])++ result = run_job(cluster)++ assert result.success+ assert not present(fake, TEAM_A, a1) and not present(fake, TEAM_A, a2) and not present(fake, TEAM_B, b1)+ 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 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)+ assert (totals.requests_pending_resent, totals.stopped_reason) == (0, "drained")+ assert result.output_for_node("publish_drain_metrics") == totals+++def test_removes_rows_for_live_and_unknown_persons_without_deleting_them(cluster: ClickhouseCluster, persons_database):+ # A live row means Postgres revived the person after the sweep queued it; an unknown row means+ # another path already hard-deleted it. Both rows must go, or they are re-sent every run.+ fake = get_active_fake()+ live = seed_live(fake, TEAM_A, 1)+ gone = seed_tombstoned(fake, TEAM_A, 2)+ unknown = str(uuid4())+ queue(persons_database, [(TEAM_A, live, SWEEP_1), (TEAM_A, gone, SWEEP_1), (TEAM_A, unknown, SWEEP_1)])++ result = run_job(cluster)++ assert queued(persons_database) == []+ assert present(fake, TEAM_A, live)+ totals = totals_of(result)+ assert (totals.persons_deleted, totals.persons_skipped_live, totals.persons_not_found) == (1, 1, 1)+++ "seed,distinct_ids_kept,resends",+ [(seed_blocked, 2, 0), (partial(seed_big, live=1), 5, 1)],+)+def test_blocked_rows_stay_queued_and_are_skipped_inside_the_retry_window(+ cluster: ClickhouseCluster, persons_database, seed, distinct_ids_kept, resends+):+ # personhog reports a tombstoned person that still owns a live distinct id, whether the person+ # fits a request or is read in a trim step on the re-send. The row must survive with blocked_at+ # set and nothing of the person deleted.+ fake = get_active_fake()+ blocked = seed(fake, TEAM_A, 1)+ gone = seed_tombstoned(fake, TEAM_A, 2)+ queue(persons_database, [(TEAM_A, blocked, SWEEP_1), (TEAM_A, gone, SWEEP_1)])++ first = run_job(cluster)++ [(team_id, person_uuid, _, blocked_at)] = queued(persons_database)+ assert (team_id, person_uuid) == (TEAM_A, blocked)+ assert blocked_at is not None+ assert present(fake, TEAM_A, blocked) and not present(fake, TEAM_A, gone)+ assert distinct_id_count(fake, TEAM_A, blocked) == distinct_ids_kept+ totals = totals_of(first)+ assert (totals.persons_blocked, totals.blocked_sample, totals.requests_pending_resent) == (1, [blocked], resends)++ second = run_job(cluster)+ assert totals_of(second).rows_read == 0, "a freshly blocked row is skipped inside the retry window"++ third = run_job(cluster, blocked_retry_hours=0)+ assert totals_of(third).persons_blocked == 1, "past the window the row is retried and reported again"+++def test_a_person_over_the_budget_is_finished_across_pending_resends_and_small_persons_never_wait(+ cluster: ClickhouseCluster, persons_database+):+ # The 5-row person comes back pending until what is left of it fits a request; the 2-row+ # person in the same request is deleted by the first call and never waits for it.+ fake = get_active_fake()+ big = seed_big(fake, TEAM_A, 1, distinct_ids=5)+ small = seed_tombstoned(fake, TEAM_A, 2)+ queue(persons_database, [(TEAM_A, big, SWEEP_1), (TEAM_A, small, SWEEP_1)])++ result = run_job(cluster)++ totals = totals_of(result)+ assert queued(persons_database) == []+ 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]] + [+ [big]+ ] * 2+ assert (totals.rpc_calls, totals.requests_pending_resent, totals.rows_deleted, totals.persons_deleted) == (+ 4,+ 3,+ 7,+ 2,+ )+ assert (totals.rows_stamped_blocked, totals.rpc_errors) == (0, 0)+++def test_pending_resends_stop_at_max_runtime_and_the_next_run_continues(+ cluster: ClickhouseCluster, persons_database, monkeypatch+):+ # Rows deleted by the calls already made stay deleted; the queue row stays put and unstamped,+ # and the next run picks the person up where it stands.+ fake = get_active_fake()+ big = seed_big(fake, TEAM_A, 1, distinct_ids=5)+ queue(persons_database, [(TEAM_A, big, SWEEP_1)])+ # The clock is read at start, before the page and before the first request; the read before+ # the pending re-send is past the deadline.+ clock = itertools.chain([0.0] * 3, itertools.repeat(10**9))+ monkeypatch.setattr(drain, "_now_monotonic", lambda: next(clock))++ first = run_job(cluster)++ totals = totals_of(first)+ assert (totals.stopped_reason, totals.rpc_calls, totals.rows_deleted) == ("max_runtime", 1, 2)+ assert queued(persons_database) == [(TEAM_A, big, SWEEP_1, None)]+ assert distinct_id_count(fake, TEAM_A, big) == 3++ second = run_job(cluster)++ assert queued(persons_database) == []+ assert not present(fake, TEAM_A, big)+ assert (totals_of(second).rpc_calls, totals_of(second).requests_pending_resent) == (2, 1)+++ "code,step_after_failure",+ [+ (grpc.StatusCode.DEADLINE_EXCEEDED, 200),+ (grpc.StatusCode.UNAVAILABLE, 200),+ (grpc.StatusCode.INTERNAL, 400),+ ],+)+def test_the_step_halves_after_a_timeout_and_doubles_after_a_run_of_successes(+ cluster: ClickhouseCluster, persons_database, monkeypatch, code, step_after_failure+):+ # A timeout halves the 400-row step to 200 before the retry; twenty successes in a row double+ # it back, capped at max_rows_per_request. Other errors leave it alone, and nothing is stamped.+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 26)]+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])+ fail_with(monkeypatch, fake, [code])++ result = run_job(cluster, rpc_batch_size=1, max_rows_per_request=400)++ assert [request.max_rows for request in delete_requests(fake)] == [step_after_failure] * 20 + [400] * 5+ totals = totals_of(result)+ assert (totals.rpc_calls, totals.rpc_errors, totals.step_rows_min, totals.step_rows_max) == (+ 25,+ 1,+ step_after_failure,+ 400,+ )+ assert queued(persons_database) == []+ assert totals.rows_stamped_blocked == 0+++def test_too_many_blocked_rows_fail_the_run(cluster: ClickhouseCluster, persons_database):+ fake = get_active_fake()+ blocked = seed_blocked(fake, TEAM_A, 1)+ queue(persons_database, [(TEAM_A, blocked, SWEEP_1)])++ result = run_job(cluster, max_blocked=0, raise_on_error=False)++ assert not result.success+ [(_, _, _, blocked_at)] = queued(persons_database)+ assert blocked_at is not None, "the row is stamped before the run gives up, so operators can find it"+ assert present(fake, TEAM_A, blocked)+ description, _ = failure_of(result)+ assert "max_blocked" in description+++def test_dry_run_counts_the_queue_without_calling_personhog_or_writing(+ cluster: ClickhouseCluster, persons_database, monkeypatch+):+ fake = get_active_fake()+ gone = seed_tombstoned(fake, TEAM_A, 1)+ queue(persons_database, [(TEAM_A, gone, SWEEP_1), (TEAM_B, str(uuid4()), SWEEP_2)])+ monkeypatch.setattr(drain, "require_personhog_client", lambda: (_ for _ in ()).throw(RuntimeError("no client")))++ result = run_job(cluster, dry_run=True)++ assert result.success+ assert delete_requests(fake) == []+ assert len(queued(persons_database)) == 2+ assert present(fake, TEAM_A, gone)+ totals = totals_of(result)+ assert (totals.rows_read, totals.teams_touched, totals.rpc_calls) == (2, {TEAM_A, TEAM_B}, 0)+++def test_every_row_is_drained_exactly_once_across_page_and_chunk_boundaries(+ cluster: ClickhouseCluster, persons_database+):+ # Pages of two and requests of one put boundaries everywhere: an off-by-one at a page edge, a+ # stop after a full final page, or a lost chunk would leave a row queued or send one twice.+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 6)]+ uuids.append(seed_tombstoned(fake, TEAM_B, 6))+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids[:5]] + [(TEAM_B, uuids[5], SWEEP_1)])++ 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]+ assert sorted(sent) == sorted(uuids)+ assert all(len(request.person_uuids) == 1 for request in delete_requests(fake))+ assert queued(persons_database) == []+ assert totals_of(result).pages == 3+++def test_max_persons_caps_the_run_and_the_next_run_finishes_the_rest(cluster: ClickhouseCluster, persons_database):+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 6)]+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])++ capped = run_job(cluster, max_persons=2, page_size=1000)++ assert totals_of(capped).stopped_reason == "max_persons"+ assert totals_of(capped).persons_deleted == 2+ assert len(queued(persons_database)) == 3++ rest = run_job(cluster)++ assert totals_of(rest).persons_deleted == 3+ assert queued(persons_database) == []+++def test_rows_from_two_sweeps_are_sent_separately_and_a_requeued_row_survives(+ cluster: ClickhouseCluster, persons_database, monkeypatch+):+ # Rows of one team from two sweep runs travel in separate requests so the queue delete can pin+ # deleted_at. A row the sweep re-queues mid-flight keeps the newer deleted_at and is drained+ # next run instead of being deleted on stale evidence.+ fake = get_active_fake()+ old = seed_tombstoned(fake, TEAM_A, 1)+ new = seed_tombstoned(fake, TEAM_A, 2)+ requeued = seed_tombstoned(fake, TEAM_A, 3)+ requeued_blocked = seed_blocked(fake, TEAM_A, 4)+ queue(+ persons_database,+ [+ (TEAM_A, old, SWEEP_1),+ (TEAM_A, requeued, SWEEP_1),+ (TEAM_A, requeued_blocked, SWEEP_1),+ (TEAM_A, new, SWEEP_2),+ ],+ )+ original = fake.delete_tombstoned_persons++ def requeue_during_rpc(+ request: DeleteTombstonedPersonsRequest, timeout: float | None = None+ ) -> DeleteTombstonedPersonsResponse:+ if requeued in request.person_uuids:+ with persons_database.cursor() as cursor:+ cursor.execute(+ f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET deleted_at = %s WHERE person_uuid = ANY(%s::uuid[])",+ (SWEEP_2, [requeued, requeued_blocked]),+ )+ persons_database.commit()+ return original(request, timeout=timeout)++ monkeypatch.setattr(fake, "delete_tombstoned_persons", requeue_during_rpc)++ result = run_job(cluster)++ sent = [sorted(request.person_uuids) 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.+ assert queued(persons_database) == sorted(+ [(TEAM_A, requeued, SWEEP_2, None), (TEAM_A, requeued_blocked, SWEEP_2, None)], key=lambda row: row[1]+ )+ assert totals_of(result).queue_rows_deleted == 2+ # The stamp the guard refused must not count toward max_blocked either.+ assert (totals_of(result).rows_stamped_blocked, totals_of(result).blocked_sample) == (0, [])+++ "codes,window,expect_success",+ [+ ([grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.INTERNAL, grpc.StatusCode.UNAVAILABLE], 900.0, True),+ ([grpc.StatusCode.UNAVAILABLE] * 50, 0.0, False),+ ],+)+def test_rpc_failures_are_retried_inside_the_window_and_fail_the_run_after_it(+ cluster: ClickhouseCluster, persons_database, monkeypatch, codes, window, expect_success+):+ # Inside the window every failure is retried whatever its code; past it the run fails with the+ # request in the failure, its rows in place and nothing stamped, so a rerun finishes the work.+ fake = get_active_fake()+ gone = seed_tombstoned(fake, TEAM_A, 1)+ queue(persons_database, [(TEAM_A, gone, SWEEP_1)])+ fail_with(monkeypatch, fake, codes)+ emitted = record_emits(monkeypatch)++ result = run_job(cluster, rpc_retry_window_seconds=window, raise_on_error=False)++ assert result.success is expect_success+ if expect_success:+ assert queued(persons_database) == []+ assert (totals_of(result).rpc_errors, totals_of(result).rpc_calls) == (len(codes), 1)+ return+ assert queued(persons_database) == [(TEAM_A, gone, SWEEP_1, None)]+ assert present(fake, TEAM_A, gone)+ description, metadata = failure_of(result)+ assert "stay queued for the next run" in description+ assert (metadata["team_id"].value, metadata["first_uuid"].value, metadata["sent_size"].value) == (TEAM_A, gone, 1)+ assert (metadata["attempts"].value, metadata["grpc_code"].value) == (1, "UNAVAILABLE")+ assert metadata["rows_stamped_blocked"].value == 0+ # A failed run still reports what it did, or dashboards see a silent gap instead of a failure.+ assert ("person_pg_cleanup_drain_runs", {"stopped_reason": "failed", "dry_run": "false"}) in emitted+ assert ("person_pg_cleanup_drain_rpc_calls", {"result": "error", "code": "UNAVAILABLE"}) in emitted+++ "code", [grpc.StatusCode.UNIMPLEMENTED, grpc.StatusCode.INVALID_ARGUMENT, grpc.StatusCode.PERMISSION_DENIED]+)+def test_a_fatal_rpc_code_fails_immediately_without_retrying_or_writing(+ cluster: ClickhouseCluster, persons_database, monkeypatch, code+):+ # An older personhog answers UNIMPLEMENTED, and a wrong or unauthorized request gets the same+ # answer every time. The legacy delete RPC has no tombstone check, so the run must stop rather+ # than fall back to it.+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 3)]+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])+ fail_with(monkeypatch, fake, [code] * 5)++ result = run_job(cluster, raise_on_error=False)++ assert not result.success+ assert len(delete_requests(fake)) == 0, "the wrapper raised before the fake recorded a call"+ assert queued(persons_database) == sorted((TEAM_A, uuid, SWEEP_1, None) for uuid in uuids)+ assert all(present(fake, TEAM_A, uuid) for uuid in uuids)+ _, metadata = failure_of(result)+ assert metadata["rpc_errors"].value == 1, "one attempt and no retry"+++ "overrides,expected_deleted,stopped_reason",+ [({}, 1, "max_runtime"), ({"max_runtime_seconds": 0}, 3, "drained")],+)+def test_max_runtime_stops_between_pages_unless_disabled(+ cluster: ClickhouseCluster, persons_database, monkeypatch, overrides, expected_deleted, stopped_reason+):+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 4)]+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])+ # The deadline is read once at start and checked before each page and each request. The clock+ # stands still through the first request and jumps past any finite deadline afterwards.+ clock = itertools.chain([0.0] * 3, itertools.repeat(10**9))+ monkeypatch.setattr(drain, "_now_monotonic", lambda: next(clock))++ result = run_job(cluster, page_size=1, **overrides)++ totals = totals_of(result)+ assert (totals.stopped_reason, totals.persons_deleted) == (stopped_reason, expected_deleted)+ assert len(queued(persons_database)) == 3 - expected_deleted++[email protected]("failing", ["rpc", "pg"])+def test_max_runtime_ends_a_retry_loop_cleanly(cluster: ClickhouseCluster, persons_database, monkeypatch, failing):+ # A request or statement that keeps failing must not retry past the deadline: the run stops+ # with max_runtime instead of failing, the row stays queued and nothing is stamped.+ fake = get_active_fake()+ gone = seed_tombstoned(fake, TEAM_A, 1)+ queue(persons_database, [(TEAM_A, gone, SWEEP_1)])+ if failing == "rpc":+ fail_with(monkeypatch, fake, [grpc.StatusCode.UNAVAILABLE] * 50)+ else:+ monkeypatch.setattr(+ drain, "_delete_queue_rows", lambda *args: (_ for _ in ()).throw(psycopg2.OperationalError("lost"))+ )+ record_pauses(monkeypatch)+ # Read at start, before the page and before the request; the check inside the retry loop is+ # past the deadline.+ clock = itertools.chain([0.0] * 3, itertools.repeat(10**9))+ monkeypatch.setattr(drain, "_now_monotonic", lambda: next(clock))++ result = run_job(cluster)++ assert result.success+ totals = totals_of(result)+ assert totals.stopped_reason == "max_runtime"+ assert (totals.rpc_errors, totals.rpc_calls) == ((1, 0) if failing == "rpc" else (0, 1))+ assert queued(persons_database) == [(TEAM_A, gone, SWEEP_1, None)]+ assert totals.rows_stamped_blocked == 0+++ "errors,window,expect_success,expected_connects,message",+ [+ ([psycopg2.OperationalError("server closed the connection unexpectedly")], 600.0, True, 2, ""),+ ([psycopg2.InterfaceError("connection already closed")] * 50, 0.0, False, 1, "kept failing"),+ ([_pg_error("23505")], 600.0, False, 1, "statement failed"),+ ],+)+def test_queue_statement_failures_reconnect_and_retry_inside_the_window(+ cluster: ClickhouseCluster,+ persons_database,+ monkeypatch,+ errors,+ window,+ expect_success,+ expected_connects,+ message,+):+ # A lost connection is reopened and the idempotent statement run again after a backoff; a+ # connection lost past the window, or an error no retry can clear, fails the run.+ fake = get_active_fake()+ gone = seed_tombstoned(fake, TEAM_A, 1)+ queue(persons_database, [(TEAM_A, gone, SWEEP_1)])+ pending = list(errors)+ original_delete = drain._delete_queue_rows++ def flaky_delete(cursor, chunk, person_uuids):+ if pending:+ raise pending.pop(0)+ return original_delete(cursor, chunk, person_uuids)++ connects: list[str] = []+ original_connect = drain._connect++ def counting_connect(url: str):+ connects.append(url)+ return original_connect(url)++ monkeypatch.setattr(drain, "_delete_queue_rows", flaky_delete)+ monkeypatch.setattr(drain, "_connect", counting_connect)+ pauses = record_pauses(monkeypatch)++ result = run_job(cluster, pg_retry_window_seconds=window, raise_on_error=False)++ assert result.success is expect_success+ assert len(connects) == expected_connects+ if expect_success:+ assert queued(persons_database) == []+ assert totals_of(result).pg_reconnects == 1+ assert drain.PG_RETRY_BACKOFF_SECONDS in pauses+ return+ description, metadata = failure_of(result)+ assert message in description+ assert metadata["pg_reconnects"].value == 0+ # personhog had already answered, so the person is gone; the row stays and resolves as not+ # found on the next run.+ assert queued(persons_database) == [(TEAM_A, gone, SWEEP_1, None)]+++ "rows,rpc_batch_size,expected",+ [+ ([], 3, []),+ (+ [+ QueueRow(team_id=1, person_uuid="a", deleted_at=SWEEP_1),+ QueueRow(team_id=1, person_uuid="b", deleted_at=SWEEP_1),+ ],+ 3,+ [Chunk(team_id=1, deleted_at=SWEEP_1, person_uuids=("a", "b"))],+ ),+ (+ [+ 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),+ ],+ 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",)),+ ],+ ),+ (+ [QueueRow(team_id=1, person_uuid=uuid, deleted_at=SWEEP_1) 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",)),+ ],+ ),+ ],+)+def test_chunks_for_page_groups_by_team_and_sweep_then_splits(rows, rpc_batch_size, expected):+ assert chunks_for_page(rows, rpc_batch_size) == expected+++ "exc,expected",+ [+ (_pg_error("40001"), "retry"),+ (_pg_error("40P01"), "retry"),+ (_pg_error("55P03"), "retry"),+ (_pg_error("57014"), "retry"),+ # lock_timeout arrives as an OperationalError subclass: the same connection retries it.+ (type("_LockNotAvailable", (psycopg2.OperationalError,), {"pgcode": "55P03"})(), "retry"),+ (psycopg2.OperationalError("server closed the connection unexpectedly"), "reconnect"),+ (psycopg2.InterfaceError("connection already closed"), "reconnect"),+ (_pg_error("23505"), None),+ (_pg_error(None), None),+ (RuntimeError("not postgres"), None),+ ],+)+def test_pg_recovery(exc, expected):+ assert pg_recovery(exc) == expected+++ "base,failures,expected",+ [(2.0, 1, 2.0), (2.0, 4, 16.0), (2.0, 6, 60.0), (0.0, 3, 0.0)],+)+def test_backoff_doubles_per_failure_up_to_the_cap(base, failures, expected):+ assert backoff_seconds(base, failures) == expected+++def test_pauses_after_every_request_by_pause_ms_plus_latency(cluster: ClickhouseCluster, persons_database, monkeypatch):+ # The pause is the drain's only throttle on the persons writer. Removing it, or applying it+ # per page instead of per request, would turn a bounded background job into a burst.+ fake = get_active_fake()+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 4)]+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])+ pauses = record_pauses(monkeypatch)++ result = run_job(cluster, rpc_batch_size=1, pause_ms=250, latency_multiplier=2.0)++ totals = totals_of(result)+ assert len(pauses) == totals.rpc_calls == 3+ assert all(pause >= 0.25 for pause in pauses), pauses+ assert round(sum(pause - 0.25 for pause in pauses), 6) == round(2.0 * totals.rpc_seconds_total, 6)+ assert 0 < totals.rpc_seconds_last <= totals.rpc_seconds_max <= totals.rpc_seconds_total+++@contextmanager+def _capturing_push(registry: CollectorRegistry) -> Iterator[CollectorRegistry]:+ yield registry+++def publish(totals: DrainTotals) -> tuple[CollectorRegistry, list[str]]:+ registry = CollectorRegistry()+ pushed_jobs: list[str] = []++ def fake_push(job: str) -> AbstractContextManager[CollectorRegistry]:+ pushed_jobs.append(job)+ return _capturing_push(registry)++ with patch.object(drain, "pushed_metrics_registry", fake_push):+ drain.publish_drain_metrics(dagster.build_op_context(), totals)+ return registry, pushed_jobs+++def test_a_dry_run_publishes_no_metrics():+ registry, pushed_jobs = publish(DrainTotals(dry_run=True, rows_read=5))++ # The helper pushes with PUT, which replaces the whole job. Entering it with an empty+ # registry would delete the last-success gauge, so not entering it at all is the assertion.+ assert pushed_jobs == []+ assert list(registry.collect()) == []+++def test_publishes_every_measurement_the_run_took():+ totals = DrainTotals(+ rows_read=5,+ persons_deleted=3,+ persons_blocked=1,+ rows_deleted=40,+ rows_stamped_blocked=1,+ requests_pending_resent=4,+ queue_rows_estimate_at_start=1000,+ step_rows_min=250,+ rpc_errors=2,+ pg_reconnects=1,+ rpc_seconds_max=1.5,+ )++ registry, pushed_jobs = publish(totals)++ assert pushed_jobs == [drain.DRAIN_METRICS_JOB]+ prefix = "posthog_person_pg_cleanup_drain_"+ assert {+ name: registry.get_sample_value(f"{prefix}{name}")+ for name in (+ "queue_rows_estimate_at_start",+ "rows_read",+ "persons_deleted",+ "persons_blocked",+ "rows_deleted",+ "rows_stamped_blocked",+ "requests_pending_resent",+ "step_rows_min",+ "rpc_errors",+ "pg_reconnects",+ "rpc_seconds_max",+ )+ } == {+ "queue_rows_estimate_at_start": 1000,+ "rows_read": 5,+ "persons_deleted": 3,+ "persons_blocked": 1,+ "rows_deleted": 40,+ "rows_stamped_blocked": 1,+ "requests_pending_resent": 4,+ "step_rows_min": 250,+ "rpc_errors": 2,+ "pg_reconnects": 1,+ "rpc_seconds_max": 1.5,+ }+ last_success = registry.get_sample_value(f"{prefix}last_success_timestamp_seconds")+ # Wall clock, not the monotonic clock used elsewhere here: the alert subtracts it from time().+ assert last_success is not None+ assert abs(last_success - time.time()) < 60+++ "overrides,message",+ [+ ({"rpc_timeout_seconds": 0}, "must be positive"),+ ({"max_runtime_seconds": -1}, "must not be negative"),+ ({"blocked_retry_hours": -1}, "must not be negative"),+ ({"rpc_batch_size": drain.RPC_MAX_UUIDS + 1}, "rpc_batch_size must be between"),+ ({"page_size": 0}, "page_size must be between"),+ ({"max_rows_per_request": drain.STEP_FLOOR_ROWS - 1}, "max_rows_per_request must be between"),+ ({"max_rows_per_request": drain.REPLICA_MAX_ROWS + 1}, "max_rows_per_request must be between"),+ ({"pause_ms": -1}, "must not be negative"),+ ({"max_blocked": -1}, "must not be negative"),+ ({"rpc_retry_window_seconds": -1}, "must not be negative"),+ ({"pg_retry_window_seconds": -1}, "must not be negative"),+ ],+)+def test_config_rejects_out_of_range_values(overrides, message):+ with pytest.raises(ValueError, match=message):+ drain.DrainConfig(**overrides)