: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
fix(persons): reshape person_pg_cleanup_queue for the Postgres drain (#97993)
Eli Reismana3882dbc1bde
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex 9c5743a7f0ac..b89cbbd15cfe 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -1102,7 +1102,8 @@ def persist_deleted_persons(The queue is advisory, never authoritative. Rows sit here until the drain runs, so a personcan be revived after being queued no matter how carefully this op checks. ClickHouse alsotrails Postgres, so a person revived in Postgres can still read as deleted here. The drain- has to re-verify each person against Postgres before deleting it.+ has to re-verify each person against Postgres before deleting it, and it deletes a queue row+ once the person is resolved either way."""if run.dry_run:context.log.info("dry run: skipping the write to %s", PG_CLEANUP_QUEUE_TABLE)@@ -1152,22 +1153,21 @@ def persist_deleted_persons(page = cluster.any_host_by_role(partial(read_page, after=after), NodeRole.DATA).result()if not page:break- # A person can be deleted, drained, re-created and deleted again under the same uuid,- # and the drain only looks at rows where cleaned_at is null. Leaving an already-cleaned- # row untouched would drop that second deletion on the floor and leak its Postgres rows- # for good, so the conflict re-arms the row instead of ignoring it. The WHERE keeps a- # retried op from rewriting rows that already hold these values: an unconditional- # DO UPDATE writes a new tuple version per row, so a retry over millions of rows would- # leave that many dead tuples for the persons writer to vacuum.+ # A row still pending from an earlier sweep takes this run's deleted_at, and if the drain+ # had marked it blocked (tombstoned person still owning a live distinct id) the block is+ # lifted, because a fresh ClickHouse tombstone is new evidence the drain should act on.+ # The WHERE keeps a retried op from rewriting rows that already hold this run's+ # deleted_at: an unconditional DO UPDATE writes a new tuple version per row, so a retry+ # over millions of rows would leave that many dead tuples for the persons writer to+ # vacuum.execute_values(cursor,f"""INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at)VALUES %sON CONFLICT (team_id, person_uuid) DO UPDATE- SET deleted_at = EXCLUDED.deleted_at, cleaned_at = NULL- WHERE {PG_CLEANUP_QUEUE_TABLE}.cleaned_at IS NOT NULL- OR {PG_CLEANUP_QUEUE_TABLE}.deleted_at IS DISTINCT FROM EXCLUDED.deleted_at+ SET deleted_at = EXCLUDED.deleted_at, blocked_at = NULL+ WHERE {PG_CLEANUP_QUEUE_TABLE}.deleted_at IS DISTINCT FROM EXCLUDED.deleted_at""",[(team_id, str(person_id), deleted_at) for team_id, person_id in page],page_size=1000,diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.pyindex c755ec5f10dd..70d740e0439f 100644--- a/posthog/dags/tests/test_clickhouse_cleanup.py+++ b/posthog/dags/tests/test_clickhouse_cleanup.py@@ -189,7 +189,7 @@ def seed_decoy_run(cluster: ClickhouseCluster, spared_person: str, spared_distindef queued_rows(conn) -> list[tuple]:with conn.cursor() as cursor:- cursor.execute(f"SELECT team_id, person_uuid, deleted_at, cleaned_at FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 2")+ cursor.execute(f"SELECT team_id, person_uuid, deleted_at, blocked_at FROM {PG_CLEANUP_QUEUE_TABLE} ORDER BY 2")return cursor.fetchall()@@ -294,10 +294,10 @@ def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, perrows = queued_rows(persons_database)assert len(rows) == 1- team_id, person_uuid, deleted_at, cleaned_at = rows[0]+ team_id, person_uuid, deleted_at, blocked_at = rows[0]assert (team_id, str(person_uuid)) == (TEAM_ID, deleted)assert deleted_at is not None- assert cleaned_at is None+ assert blocked_at is None# A second run must not raise on the primary key: it re-queues persons the drain has not# reached yet.@@ -319,16 +319,20 @@ def test_queues_every_person_across_page_boundaries(cluster: ClickhouseCluster,@pytest.mark.django_db-def test_requeues_a_person_the_drain_already_cleaned(cluster: ClickhouseCluster, persons_database):- # A person can be deleted, drained, then re-created and deleted again under the same uuid. The- # drain only reads rows where cleaned_at is null, so leaving the cleaned row untouched would- # drop the second deletion and leak that person's Postgres rows for good.+def test_resweeping_a_pending_person_refreshes_deleted_at_and_clears_blocked_at(+ cluster: ClickhouseCluster, persons_database+):+ # A row the drain marked blocked (tombstoned person still owning a live distinct id) stays+ # queued. When ClickHouse tombstones the same person again, the sweep must hand the drain+ # fresh evidence: the new deleted_at and a cleared block. Ignoring the conflict would leave+ # the row blocked forever and leak that person's Postgres rows for good.deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)run_job(cluster, persons_database)+ [(_, _, first_deleted_at, _)] = queued_rows(persons_database)- # Stand in for the drain having processed it.+ # Stand in for the drain having found the person blocked.with persons_database.cursor() as cursor:- cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET cleaned_at = now()")+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET blocked_at = now()")persons_database.commit()assert queued_rows(persons_database)[0][3] is not None@@ -338,7 +342,8 @@ def test_requeues_a_person_the_drain_already_cleaned(cluster: ClickhouseCluster,rows = queued_rows(persons_database)assert len(rows) == 1, "the row is keyed on (team_id, person_uuid), so this stays a single row"- assert rows[0][3] is None, "cleaned_at must be cleared so the drain picks the person up again"+ assert rows[0][2] > first_deleted_at, "deleted_at must move to the later sweep"+ assert rows[0][3] is None, "blocked_at must be cleared so the drain retries the person"def _foreign_run_dictionary(cluster: ClickhouseCluster, run_id: str) -> clickhouse_cleanup.SnapshotDictionary:@@ -548,7 +553,7 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_ddef queue_row() -> tuple:# xmin changes on every UPDATE, so a stable xmin proves no new tuple version was written.with persons_database.cursor() as cursor:- cursor.execute(f"SELECT xmin::text, deleted_at, cleaned_at FROM {PG_CLEANUP_QUEUE_TABLE}")+ cursor.execute(f"SELECT xmin::text, deleted_at, blocked_at FROM {PG_CLEANUP_QUEUE_TABLE}")[row] = cursor.fetchall()return row@@ -558,15 +563,15 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_dclickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)assert queue_row() == first- # A drained row must still be re-armed even when deleted_at matches, or the second deletion- # of a re-created person is dropped.+ # A blocked row is not touched by a same-run retry either: only a newer deleted_at is evidence+ # the drain should try again, and rewriting the row here would defeat the no-dead-tuple guard.with persons_database.cursor() as cursor:- cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET cleaned_at = now()")+ cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET blocked_at = now()")persons_database.commit()+ blocked = queue_row()clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)- rearmed = queue_row()- assert rearmed[2] is None- assert rearmed[0] != first[0]+ assert queue_row() == blocked+ assert blocked[2] is not None@pytest.mark.django_dbdiff --git a/rust/persons_migrations/20260910000001_reshape_person_pg_cleanup_queue_for_drain.sql b/rust/persons_migrations/20260910000001_reshape_person_pg_cleanup_queue_for_drain.sqlnew file mode 100644index 000000000000..8fa3a2e8e47b--- /dev/null+++ b/rust/persons_migrations/20260910000001_reshape_person_pg_cleanup_queue_for_drain.sql@@ -0,0 +1,33 @@+-- Reshape the handoff queue for the Postgres drain (posthog/dags/person_pg_cleanup_drain.py).+--+-- The drain pages the primary key by keyset and DELETEs each row once personhog has resolved+-- its person, so:+--+-- * cleaned_at was a completion marker for a drain that kept its rows. A drained row no longer+-- exists, so the column carries nothing.+-- * person_pg_cleanup_queue_drain, the partial index on (deleted_at), cannot page the queue:+-- every row of one sweep run carries the same deleted_at, so a keyset over it never advances.+-- The primary key is the drain's scan order.+-- * blocked_at records a row the drain could not resolve on its own: personhog reported the+-- person tombstoned but still owning a live distinct id, or owning more distinct ids than one+-- delete transaction may touch, or the delete request kept failing. The drain skips such rows+-- until a retry interval passes, and operators find them with WHERE blocked_at IS NOT NULL. The+-- sweep clears it when it queues the same person again.+--+-- SAFE: metadata-only ALTERs and an index drop on a small table that only the sweep and the+-- drain touch. Each statement takes a brief ACCESS EXCLUSIVE lock; no table rewrite. Idempotent.++SET LOCAL lock_timeout = '5s';++DROP INDEX IF EXISTS person_pg_cleanup_queue_drain;++ALTER TABLE person_pg_cleanup_queue DROP COLUMN IF EXISTS cleaned_at;++ALTER TABLE person_pg_cleanup_queue ADD COLUMN IF NOT EXISTS blocked_at TIMESTAMP WITH TIME ZONE;++COMMENT ON TABLE person_pg_cleanup_queue IS+ 'Persons the ClickHouse sweep removed, awaiting a Postgres hard delete by person_pg_cleanup_drain_job. Rows are deleted once drained.';+COMMENT ON COLUMN person_pg_cleanup_queue.deleted_at IS+ 'When the ClickHouse sweep finished removing the person; one value per sweep run.';+COMMENT ON COLUMN person_pg_cleanup_queue.blocked_at IS+ 'Set when the drain could not resolve the person: a live distinct id remains, the person owns too many distinct ids, or the delete request kept failing. Cleared when the sweep queues the person again.';