: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(clickhouse): connect to the persons queue inside the sweep op (#92072)
Eli Reismand70afdc96075
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex e77a48387bcf..cbd9697fb1f3 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -20,8 +20,8 @@ from math import ceilfrom django.conf import settingsimport dagster+import psycopg2import pydantic-import psycopg2.extensionsfrom clickhouse_driver.client import Clientfrom prometheus_client import Counterfrom psycopg2.extras import execute_values@@ -989,7 +989,7 @@ def delete_orphaned_distinct_ids(def persist_deleted_persons(context: dagster.OpExecutionContext,cluster: dagster.ResourceParam[ClickhouseCluster],- persons_database: dagster.ResourceParam[psycopg2.extensions.connection],+ persons_database_url: dagster.ResourceParam[str],run: CleanupRun,) -> CleanupRun:"""Hand the swept persons to Postgres, before the step that makes them unrecoverable.@@ -1003,6 +1003,12 @@ def persist_deleted_persons(context.log.info("dry run: skipping the write to %s", PG_CLEANUP_QUEUE_TABLE)return run+ # Connected here rather than at resource init: a connect failure at init happens before the+ # step exists, so no failure hook runs and the run's dictionaries are stranded. Failing+ # inside the op is a step failure, which is what lets drop_assets_on_failure fire. It also+ # keeps a dry run from dialing Postgres at all.+ persons_database = psycopg2.connect(persons_database_url, connect_timeout=10)+def read_page(client: Client, after: tuple[int, str] | None) -> list[tuple[int, str]]:# Reads the snapshot directly rather than the dictionary's query, so adding attributes to# the dictionary cannot silently change the shape of what gets queued. Keyset pagination@@ -1030,46 +1036,49 @@ def persist_deleted_persons(deleted_at = run.distinct_ids_deleted_atwritten = 0after: tuple[int, str] | None = None- with persons_database.cursor() as cursor:- cursor.execute("SET application_name = 'clickhouse_cleanup'")- # Bounded so a lock conflict on the queue fails the page instead of holding a transaction- # open on the persons writer; the per-page upsert is idempotent, so a retry is safe.- cursor.execute("SET statement_timeout = '120s'")- cursor.execute("SET lock_timeout = '10s'")- while True:- 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.- execute_values(- cursor,- f"""- INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at)- VALUES %s- ON 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- """,- [(team_id, str(person_id), deleted_at) for team_id, person_id in page],- page_size=1000,- )- # The conflict guard makes rowcount "rows changed", not "rows queued"; the metric is- # the queued set, which is the page.- written += len(page)- # Commit per page: the upsert makes replays idempotent, and one transaction across- # millions of rows would hold WAL and xmin on the persons writer for the whole op.- persons_database.commit()- if len(page) < PERSIST_PAGE_SIZE:- break- last_team, last_person = page[-1]- after = (last_team, str(last_person))+ try:+ with persons_database.cursor() as cursor:+ cursor.execute("SET application_name = 'clickhouse_cleanup'")+ # Bounded so a lock conflict on the queue fails the page instead of holding a transaction+ # open on the persons writer; the per-page upsert is idempotent, so a retry is safe.+ cursor.execute("SET statement_timeout = '120s'")+ cursor.execute("SET lock_timeout = '10s'")+ while True:+ 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.+ execute_values(+ cursor,+ f"""+ INSERT INTO {PG_CLEANUP_QUEUE_TABLE} (team_id, person_uuid, deleted_at)+ VALUES %s+ ON 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+ """,+ [(team_id, str(person_id), deleted_at) for team_id, person_id in page],+ page_size=1000,+ )+ # The conflict guard makes rowcount "rows changed", not "rows queued"; the metric is+ # the queued set, which is the page.+ written += len(page)+ # Commit per page: the upsert makes replays idempotent, and one transaction across+ # millions of rows would hold WAL and xmin on the persons writer for the whole op.+ persons_database.commit()+ if len(page) < PERSIST_PAGE_SIZE:+ break+ last_team, last_person = page[-1]+ after = (last_team, str(last_person))+ finally:+ persons_database.close()context.add_output_metadata({"queued_for_postgres": dagster.MetadataValue.int(written)})return rundiff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex d76c5319dfa0..b84eb7ce6d32 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -223,6 +223,8 @@ class PostgresResource(dagster.ConfigurableResource):password: strdef create_resource(self, context: dagster.InitResourceContext) -> psycopg2.extensions.connection:+ # Without a timeout a blackholed route hangs this connect for the OS TCP timeout+ # (about two minutes) and the step emits nothing while it waits.return psycopg2.connect(host=self.host,port=int(self.port),@@ -230,6 +232,7 @@ class PostgresResource(dagster.ConfigurableResource):user=self.user,password=self.password,cursor_factory=psycopg2.extras.RealDictCursor,+ connect_timeout=10,)@@ -273,6 +276,20 @@ class PostgresURLResource(dagster.ConfigurableResource):return pg.create_resource(context)+class PostgresURL(dagster.ConfigurableResource):+ """A Postgres connection URL handed to the op unopened.++ An op that connects in its own body turns a connect failure into a step failure, which is+ what lets failure hooks run; a connection opened at resource init fails before the step+ exists and no hook fires. It also lets a dry run skip the connect entirely.+ """++ connection_url: str++ def create_resource(self, context: dagster.InitResourceContext) -> str:+ return self.connection_url++@dagster.resourcedef kafka_producer_resource(context: dagster.InitResourceContext) -> Generator[_KafkaProducer]:"""Yield a singleton Kafka producer bound to the INGESTION (WarpStream) profile; flush on teardown.diff --git a/posthog/dags/locations/__init__.py b/posthog/dags/locations/__init__.pyindex 48ec406f4fc7..432c49fec540 100644--- a/posthog/dags/locations/__init__.py+++ b/posthog/dags/locations/__init__.py@@ -10,6 +10,7 @@ from posthog.dags.common.resources import (ClayWebhookResource,ClickhouseClusterResource,PostgresResource,+ PostgresURL,PostgresURLResource,PostHogAnalyticsResource,RedisResource,@@ -49,6 +50,9 @@ resources_by_env = {"persons_database": PostgresURLResource(connection_url=dagster.EnvVar("PERSONS_DB_WRITER_URL"),),+ "persons_database_url": PostgresURL(+ connection_url=dagster.EnvVar("PERSONS_DB_WRITER_URL"),+ ),# Kafka producer (auto-configured from Django settings)"kafka_producer": kafka_producer_resource,# Clay webhook for job switchers pipeline@@ -85,6 +89,9 @@ resources_by_env = {"persons_database": PostgresURLResource(connection_url=dagster.EnvVar("PERSONS_DB_WRITER_URL"),),+ "persons_database_url": PostgresURL(+ connection_url=dagster.EnvVar("PERSONS_DB_WRITER_URL"),+ ),# Kafka producer (auto-configured from Django settings)"kafka_producer": kafka_producer_resource,# Clay webhook for job switchers pipelinediff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.pyindex 4a695b4609b1..f5121126a6df 100644--- a/posthog/dags/tests/test_clickhouse_cleanup.py+++ b/posthog/dags/tests/test_clickhouse_cleanup.py@@ -11,6 +11,7 @@ from unittest.mock import patchimport dagsterimport psycopg2from clickhouse_driver import Client+from psycopg2 import OperationalErrorfrom posthog.clickhouse.cleanup_snapshots import (CLEANUP_DELETED_PERSONS_TABLE,@@ -56,7 +57,7 @@ def persons_database() -> Iterator[psycopg2.extensions.connection]:def run_job(cluster: ClickhouseCluster, persons_database, run_config=RUN_FOR_REAL, raise_on_error=True):return clickhouse_deletion_sweep_job.execute_in_process(run_config=run_config,- resources={"cluster": cluster, "persons_database": persons_database},+ resources={"cluster": cluster, "persons_database_url": persons_db_url(writer=True)},raise_on_error=raise_on_error,)@@ -339,6 +340,42 @@ def test_requeues_a_person_the_drain_already_cleaned(cluster: ClickhouseCluster,assert rows[0][3] is None, "cleaned_at must be cleared so the drain picks the person up again"+def test_a_dry_run_never_dials_postgres(cluster: ClickhouseCluster, persons_database):+ # The EU dry run failed at Postgres resource init on a network path a dry run never needed.+ # Connecting inside the op, after the dry-run return, keeps a dry run ClickHouse-only.+ run = clickhouse_cleanup.CleanupRun.for_run("dry_run_no_pg", clickhouse_cleanup.CleanupConfig(dry_run=True))+ with patch.object(clickhouse_cleanup.psycopg2, "connect", side_effect=AssertionError("dialed postgres")):+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, "postgres://unused", run)+++def test_a_postgres_connect_failure_drops_the_dictionaries(cluster: ClickhouseCluster, persons_database):+ # A connect failure at resource init happens before the step exists, so the failure hook+ # never ran and the run's dictionaries survived on every host. Connecting inside the op+ # makes it a step failure, and the hook must clean up.+ create_person(team_id=TEAM_ID, version=0, is_deleted=True)++ real_connect = psycopg2.connect++ def refuse_dsn_connects(*args, **kwargs):++ # Only the op passes a single DSN string; Django's own connections use kwargs and must++ # keep working, or the cohort op fails first and the wrong step trips the hook.++ if args and isinstance(args[0], str):+ raise OperationalError("connection timed out")++ return real_connect(*args, **kwargs)++ with patch.object(clickhouse_cleanup.psycopg2, "connect", side_effect=refuse_dsn_connects):+ result = run_job(cluster, persons_database, raise_on_error=False)++ assert not result.success+ assert cluster.any_host(dictionaries_for_run(result.run_id)).result() == 0++@pytest.mark.django_dbdef test_a_capped_run_deletes_a_slice_and_the_next_run_drains_the_rest(cluster: ClickhouseCluster, persons_database):# max_persons bounds one run's blast radius; correctness across runs holds because whatever@@ -401,10 +438,10 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_d[row] = cursor.fetchall()return row- clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)first = queue_row()- clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)+ clickhouse_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@@ -412,7 +449,7 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_dwith persons_database.cursor() as cursor:cursor.execute(f"UPDATE {PG_CLEANUP_QUEUE_TABLE} SET cleaned_at = now()")persons_database.commit()- clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_database, run)+ clickhouse_cleanup.persist_deleted_persons(dagster.build_op_context(), cluster, persons_db_url(writer=True), run)rearmed = queue_row()assert rearmed[2] is Noneassert rearmed[0] != first[0]