: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
chore(persons): remove person tools that nothing runs (#111667)
Eli Reismanb36b3f46e04e
diff --git a/posthog/dags/PERSON_PROPERTY_RECONCILIATION.md b/posthog/dags/PERSON_PROPERTY_RECONCILIATION.mdindex b515792ff1fd..57dc6de1b7ff 100644--- a/posthog/dags/PERSON_PROPERTY_RECONCILIATION.md+++ b/posthog/dags/PERSON_PROPERTY_RECONCILIATION.md@@ -399,5 +399,3 @@ When `backup_enabled: true`, the job stores before/after state in `posthog_perso- `properties` / `properties_after`: Before/after JSON- `version` / `version_after`: Before/after version numbers- `pending_operations`: Array of operations that were applied--To restore a person to their pre-reconciliation state, use the companion job `person_property_reconciliation_restore.py`.diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex 194ed4444d33..ce5540a7b84d 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -319,10 +319,8 @@ class PostgresURL(dagster.ConfigurableResource):def kafka_producer_resource(context: dagster.InitResourceContext) -> Generator[_KafkaProducer]:"""Yield a singleton Kafka producer bound to the INGESTION (WarpStream) profile; flush on teardown.- Every existing consumer of this resource (`detach_distinct_id_op`,- `person_property_reconciliation`, `person_property_reconciliation_restore`)- produces to `clickhouse_person` / `clickhouse_person_distinct_id`, which the- routing map sends to the INGESTION profile. Binding the resource here keeps+ Consumers of this resource produce to `clickhouse_person` / `clickhouse_person_distinct_id`,+ which the routing map sends to the INGESTION profile. Binding the resource here keepsthat explicit so a chart misconfiguration (missing `KAFKA_INGESTION_HOSTS`)fails loud rather than silently dropping writes via the DEFAULT fallback.diff --git a/posthog/dags/delete_persons_from_trigger_log.py b/posthog/dags/delete_persons_from_trigger_log.pydeleted file mode 100644index 48d9b86dfd7b..000000000000--- a/posthog/dags/delete_persons_from_trigger_log.py+++ /dev/null@@ -1,394 +0,0 @@-"""Dagster job for deleting posthog_person_new rows (cascading to N associated posthog_persondistinctid rows)-that are present in the trigger log table used to capture deletes on the unpartitioned DB while we-transitioned to the new, partitioned DB."""--import time-from typing import Any--import dagster-import psycopg2-import psycopg2.errors-from dagster_k8s import k8s_job_executor--from posthog.clickhouse.cluster import ClickhouseCluster-from posthog.clickhouse.custom_metrics import MetricsClient-from posthog.dags.common import JobOwners--MAX_RETRY_ATTEMPTS = 5---class DeletePersonsFromTriggerLogConfig(dagster.Config):- """Configuration for the delete persons from trigger log job."""-- persons_table: str = "posthog_person_new"- batch_size: int = 100 # Work in small batches since each person ID will cascade a delete to many distinct ID rows---def get_team_ids_for_dpft(- context: dagster.OpExecutionContext,- database: dagster.ResourceParam[psycopg2.extensions.connection],-) -> list[int]:- """- Query source database for all distinct team_ids from posthog_person_deletes_log table- that have corresponding records in posthog_person_new.- Returns list of team IDs to process.- """- with database.cursor() as cursor:- team_ids_query = """- SELECT DISTINCT pdl.team_id- FROM posthog_person_deletes_log AS pdl- WHERE EXISTS (- SELECT 1- FROM posthog_person_new AS p- WHERE pdl.id = p.id AND pdl.team_id = p.team_id- )- ORDER BY pdl.team_id- """- context.log.info("Querying for distinct team_ids with persons to delete")- cursor.execute(team_ids_query)- rows = cursor.fetchall()-- team_ids = [int(row["team_id"]) for row in rows]-- if not team_ids:- context.log.info("No team IDs found with persons to delete")- return []-- context.log.info(f"Found {len(team_ids)} teams with persons to delete")- context.log.info(f"Sample of teams to process: {team_ids[:10]}" + ("..." if len(team_ids) > 10 else ""))- context.add_output_metadata(- {- "team_count": dagster.MetadataValue.int(len(team_ids)),- }- )-- return team_ids--[email protected](out=dagster.DynamicOut(int))-def create_team_chunks_for_dpft(- context: dagster.OpExecutionContext,- team_ids: list[int],-):- """- Create a chunk for each team_id.- Yields DynamicOutput for each team.- """- if not team_ids:- context.log.info("No teams to process")- return-- context.log.info(f"Creating {len(team_ids)} team chunks")-- for team_id in team_ids:- chunk_key = f"team_{team_id}"- context.log.info(f"Yielding chunk for team_id: {team_id}")- yield dagster.DynamicOutput(- value=team_id,- mapping_key=chunk_key,- )---def scan_delete_chunk_for_dpft(- context: dagster.OpExecutionContext,- config: DeletePersonsFromTriggerLogConfig,- chunk: int,- database: dagster.ResourceParam[psycopg2.extensions.connection],- cluster: dagster.ResourceParam[ClickhouseCluster],-) -> dict[str, Any]:- """- Scan posthog_person_deletes_log table for all records of a specific team_id- that have an associated posthog_person_new row, and deletes the corresponding- posthog_person_new rows. Processes in batches of batch_size person IDs.- """- team_id = chunk- batch_size = config.batch_size- chunk_id = f"team_{team_id}"- job_name = context.run.job_name-- # Initialize metrics client- metrics_client = MetricsClient(cluster)-- context.log.info(f"Starting chunk scan and delete for team_id: {team_id}")-- total_records_deleted = 0- last_person_id: int | None = None- failed_last_person_id: int | None = None-- try:- with database.cursor() as cursor:- # Set session-level settings once for the entire chunk- cursor.execute("SET application_name = 'delete_persons_from_trigger_log'")- cursor.execute("SET lock_timeout = '5s'")- cursor.execute("SET statement_timeout = '30min'")- cursor.execute("SET maintenance_work_mem = '12GB'")- cursor.execute("SET work_mem = '512MB'")- cursor.execute("SET temp_buffers = '512MB'")- cursor.execute("SET max_parallel_workers_per_gather = 2")- cursor.execute("SET max_parallel_maintenance_workers = 2")- cursor.execute("SET synchronous_commit = off")-- retry_attempt = 0- while True:- try:- # Track batch start time for duration metric- batch_start_time = time.time()-- # Begin transaction (settings already applied at session level)- cursor.execute("BEGIN")-- # Query to find posthog_person_deletes_log rows for this team- # Use keyset pagination with WHERE id > last_id for efficiency- if last_person_id is None:- scan_query = f"""-SELECT pdl.id, pdl.team_id-FROM posthog_person_deletes_log AS pdl-WHERE pdl.team_id = %s- AND EXISTS (- SELECT 1- FROM {config.persons_table} AS p- WHERE pdl.id = p.id- AND pdl.team_id = p.team_id- )-ORDER BY pdl.id-LIMIT %s-"""- cursor.execute(scan_query, (team_id, batch_size))- else:- scan_query = f"""-SELECT pdl.id, pdl.team_id-FROM posthog_person_deletes_log AS pdl-WHERE pdl.team_id = %s- AND pdl.id > %s- AND EXISTS (- SELECT 1- FROM {config.persons_table} AS p- WHERE pdl.id = p.id- AND pdl.team_id = p.team_id- )-ORDER BY pdl.id-LIMIT %s-"""- cursor.execute(scan_query, (team_id, last_person_id, batch_size))-- rows = cursor.fetchall()-- # If no more rows, we're done with this team- if not rows:- cursor.execute("COMMIT")- break-- ids_to_delete = [(int(row["team_id"]), int(row["id"])) for row in rows]- # Update last_person_id for next iteration- last_person_id = ids_to_delete[-1][1]-- # Commit the transaction- cursor.execute("COMMIT")-- records_deleted = 0- for tid, person_id in ids_to_delete:- try:- context.log.info(- f"Deleting person={person_id}, team_id={tid} from {config.persons_table} "- f"(attempt {retry_attempt + 1})"- )- cursor.execute("BEGIN")- cursor.execute(- f"DELETE FROM {config.persons_table} WHERE team_id = %s AND id = %s",- (tid, person_id),- )- records_deleted += cursor.rowcount- cursor.execute("COMMIT")- except Exception as delete_error:- # bubble up errors to be retried on deadlock etc. or fail the job- context.log.exception(- f"Failed to delete person={person_id}, team_id={tid} from "- f"{config.persons_table} (attempt {retry_attempt + 1}): {delete_error}"- )- raise-- try:- metrics_client.increment(- "delete_persons_from_trigger_log_records_deleted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(records_deleted),- ).result()- except Exception:- pass # Don't fail on metrics error-- try:- metrics_client.increment(- "delete_persons_from_trigger_log_records_scanned_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(batch_size),- ).result()- except Exception:- pass-- # Track batch duration metric (IV)- batch_duration_seconds = time.time() - batch_start_time- try:- metrics_client.increment(- "delete_persons_from_trigger_log_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=batch_duration_seconds,- ).result()- except Exception:- pass-- total_records_deleted += records_deleted-- context.log.info(- f"Deleted batch: {records_deleted} records for team_id={team_id}, "- f"last_person_id={last_person_id}"- )-- # Reset retry attempt counter after successful batch- retry_attempt = 0-- except Exception as batch_error:- # Rollback transaction on error- try:- cursor.execute("ROLLBACK")- except Exception as rollback_error:- context.log.exception(- f"Failed to rollback transaction for team_id={team_id}, "- f"last_person_id={last_person_id}: {str(rollback_error)}"- )- pass # Ignore rollback errors-- # Check if error is a serialization failure, pause and retry if so- serialization_failure_class = getattr(psycopg2.errors, "SerializationFailure", None)- is_serialization_failure = (- serialization_failure_class is not None and isinstance(batch_error, serialization_failure_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40001")- if is_serialization_failure:- error_msg = (- f"Serialization failure detected for team_id={team_id}, "- f"last_person_id={last_person_id}. Error is: {batch_error}. "- "This is expected due to concurrent transactions."- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Check if error is a deadlock, pause and retry if so- deadlock_detected_class = getattr(psycopg2.errors, "DeadlockDetected", None)- is_deadlock = (- deadlock_detected_class is not None and isinstance(batch_error, deadlock_detected_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40P01")- if is_deadlock:- error_msg = (- f"Deadlock detected for team_id={team_id}, "- f"last_person_id={last_person_id}. Error is: {batch_error}. "- "This is expected due to concurrent transactions."- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Handle unexpected errors by bubbling up to dagster.Failure- failed_last_person_id = last_person_id- error_msg = (- f"Failed to scan and delete rows for team_id={team_id}, "- f"last_person_id={last_person_id}: {str(batch_error)}"- )- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "delete_persons_from_trigger_log_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "batch_scan_delete_failed"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- raise dagster.Failure(- description=error_msg,- metadata={- "team_id": dagster.MetadataValue.int(team_id),- "failed_last_person_id": dagster.MetadataValue.int(failed_last_person_id)- if failed_last_person_id- else dagster.MetadataValue.text("N/A"),- "error_message": dagster.MetadataValue.text(str(batch_error)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from batch_error-- except dagster.Failure:- # Re-raise Dagster failures as-is (they already have metadata and metrics)- raise- except Exception as e:- # Catch any other unexpected errors- error_msg = f"Unexpected error scanning and deleting for team_id={team_id}: {str(e)}"- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "delete_persons_from_trigger_log_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "unexpected_scan_delete_error"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error- raise dagster.Failure(- description=error_msg,- metadata={- "team_id": dagster.MetadataValue.int(team_id),- "failed_last_person_id": dagster.MetadataValue.int(failed_last_person_id)- if failed_last_person_id- else dagster.MetadataValue.int(last_person_id)- if last_person_id- else dagster.MetadataValue.text("N/A"),- "error_message": dagster.MetadataValue.text(str(e)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from e-- context.log.info(f"Completed team_id={team_id}: deleted {total_records_deleted} records")-- # Emit metric for chunk completion- run_id = context.run.run_id- try:- metrics_client.increment(- "distinct_ids_without_person_chunks_completed_total",- labels={"job_name": job_name, "run_id": run_id, "chunk_id": chunk_id},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- context.add_output_metadata(- {- "team_id": dagster.MetadataValue.int(team_id),- "records_deleted": dagster.MetadataValue.int(total_records_deleted),- }- )-- return {- "team_id": team_id,- "records_deleted": total_records_deleted,- }--- tags={"owner": JobOwners.TEAM_INGESTION.value},- executor_def=k8s_job_executor,-)-def delete_persons_from_trigger_log_job():- """- Scan posthog_person_deletes_log table by team_id, and deletes the corresponding- posthog_person_new rows. Each team is processed in parallel for optimal performance.- """- team_ids = get_team_ids_for_dpft()- chunks = create_team_chunks_for_dpft(team_ids)- chunks.map(scan_delete_chunk_for_dpft)diff --git a/posthog/dags/fix_missing_person_overrides.py b/posthog/dags/fix_missing_person_overrides.pydeleted file mode 100644index fd442721eff9..000000000000--- a/posthog/dags/fix_missing_person_overrides.py+++ /dev/null@@ -1,249 +0,0 @@-"""Dagster job to automatically fix missing person_id overrides.--This job detects distinct_ids where the resolved person_id (using overrides) differs-from the person_id in person_distinct_id2, indicating that a problem has occurred-during ingestion, person merges, clickhouse migration, etc. (It has hard to know-which, after the fact).-"""--from typing import Optional--import dagster-import pydantic--from posthog.hogql.query import execute_hogql_query--from posthog.clickhouse.client import sync_execute-from posthog.dags.common import JobOwners-from posthog.models import Team---class FixMissingPersonOverridesConfig(dagster.Config):- """Configuration for the fix missing person overrides job."""-- team_id: int = pydantic.Field(description="Team ID to process")- dry_run: bool = pydantic.Field(- default=True,- description="If true, don't actually insert, just log what would be inserted",- )- min_date: Optional[str] = pydantic.Field(- default=None,- description="Optional minimum date for events query (ISO format, e.g. '2024-01-01')",- )- max_date: Optional[str] = pydantic.Field(- default=None,- description="Optional maximum date for events query (ISO format, e.g. '2024-12-31')",- )---def get_mismatched_distinct_ids(- team: Team,- min_date: Optional[str] = None,- max_date: Optional[str] = None,-) -> list[str]:- """Find distinct_ids where events.person_id differs from pdi.person_id.-- This identifies distinct_ids where the event's stored person_id doesn't match- what pdi2 says it should be, indicating a missing or incorrect override.-- Args:- team: The team to query- min_date: Optional minimum date filter (ISO format)- max_date: Optional maximum date filter (ISO format)-- Returns list of distinct_ids that need to be checked.- """- from posthog.hogql import ast- from posthog.hogql.parser import parse_select-- # Select distinct_id (not person_id) so we can look up the correct person_id from pdi2- query = parse_select("SELECT DISTINCT distinct_id FROM events WHERE person_id != pdi.person_id")- assert isinstance(query, ast.SelectQuery)-- # Build date filter conditions- date_conditions: list[ast.Expr] = []-- if min_date:- date_conditions.append(- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=min_date),- )- )-- if max_date:- date_conditions.append(- ast.CompareOperation(- op=ast.CompareOperationOp.Lt,- left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=max_date),- )- )-- # Add date conditions to the WHERE clause- if date_conditions and query.where:- query.where = ast.And(exprs=[query.where, *date_conditions])-- result = execute_hogql_query(query, team=team)- return [str(row[0]) for row in result.results] if result.results else []---def get_missing_overrides_for_distinct_ids(team_id: int, distinct_ids: list[str]) -> list[tuple[str, str, int]]:- """Get (distinct_id, person_id, version) tuples that need overrides.-- For the given distinct_ids, looks up what person_id they should have according to pdi2,- and filters out any that already have overrides.-- Returns list of (distinct_id, person_id, version) tuples that need to be inserted.- """- if not distinct_ids:- return []-- result = sync_execute(- """- SELECT- distinct_id,- argMax(person_id, version) as current_person_id,- max(version) as max_version- FROM person_distinct_id2- WHERE team_id = %(team_id)s- AND distinct_id IN %(distinct_ids)s- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0- AND distinct_id NOT IN (- SELECT distinct_id- FROM person_distinct_id_overrides- WHERE team_id = %(team_id)s- AND distinct_id IN %(distinct_ids)s- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0- )- """,- {"team_id": team_id, "distinct_ids": distinct_ids},- )-- return [(row[0], str(row[1]), int(row[2])) for row in result] if result else []---def get_existing_override(team_id: int, distinct_id: str) -> Optional[tuple[str, int]]:- """Check if an override already exists (used for testing)."""- result = sync_execute(- """- SELECT- argMax(person_id, version) as pid,- max(version) as max_version- FROM person_distinct_id_overrides- WHERE team_id = %(team_id)s- AND distinct_id = %(distinct_id)s- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0- """,- {"team_id": team_id, "distinct_id": distinct_id},- )- if result and result[0]:- return str(result[0][0]), int(result[0][1])- return None---def insert_override_batch(overrides: list[tuple[int, str, str, int]]) -> None:- """Insert a batch of records into person_distinct_id_overrides.-- Args:- overrides: List of (team_id, distinct_id, person_id, version) tuples- """- if not overrides:- return-- team_ids = [t[0] for t in overrides]- distinct_ids = [t[1] for t in overrides]- person_ids = [t[2] for t in overrides]- versions = [t[3] for t in overrides]-- sync_execute(- """- INSERT INTO person_distinct_id_overrides- (team_id, distinct_id, person_id, is_deleted, version, _timestamp, _offset, _partition)- SELECT- tupleElement(t, 1) as team_id,- tupleElement(t, 2) as distinct_id,- tupleElement(t, 3) as person_id,- 0 as is_deleted,- tupleElement(t, 4) as version,- now() as _timestamp,- 0 as _offset,- 0 as _partition- FROM (- SELECT arrayJoin(arrayZip(- %(team_ids)s,- %(distinct_ids)s,- %(person_ids)s,- %(versions)s- )) as t- )- """,- {- "team_ids": team_ids,- "distinct_ids": distinct_ids,- "person_ids": person_ids,- "versions": versions,- },- )---def fix_missing_person_overrides_op(- context: dagster.OpExecutionContext,- config: FixMissingPersonOverridesConfig,-) -> None:- """- Automatically detect and fix missing person_id overrides.-- 1. Use HogQL to find distinct_ids where events.person_id != pdi.person_id- 2. Look up those distinct_ids in pdi2 to get the correct person_id- 3. Filter out distinct_ids that already have overrides- 4. Batch insert all missing overrides- """- team = Team.objects.get(id=config.team_id)-- context.log.info(f"Finding mismatched distinct_ids for team {config.team_id}")- context.log.info(f"Dry run: {config.dry_run}")- if config.min_date or config.max_date:- context.log.info(f"Date range: {config.min_date or 'start'} to {config.max_date or 'end'}")-- # Step 1: Find distinct_ids with mismatches (1 HogQL query)- mismatched_distinct_ids = get_mismatched_distinct_ids(team, config.min_date, config.max_date)- context.log.info(f"Found {len(mismatched_distinct_ids)} distinct_ids with mismatches")-- if not mismatched_distinct_ids:- context.log.info("No mismatches found, nothing to do")- return-- # Step 2: Get missing overrides - looks up pdi2 for correct person_id- missing_overrides = get_missing_overrides_for_distinct_ids(config.team_id, mismatched_distinct_ids)- context.log.info(f"Found {len(missing_overrides)} distinct_ids missing overrides")-- if not missing_overrides:- context.log.info("All distinct_ids already have overrides")- return-- # Build the batch with version > 0 so it gets picked up by the overrides MV- pending_overrides = [- (config.team_id, distinct_id, person_id, max(version, 1))- for distinct_id, person_id, version in missing_overrides- ]-- if config.dry_run:- for distinct_id, person_id, _version in missing_overrides:- context.log.info(f" [DRY RUN] Would insert -> distinct_id={distinct_id}, person_id={person_id}...")- context.log.info(f"[DRY RUN] Would have inserted {len(pending_overrides)} overrides")- else:- # Step 3: Batch insert all missing overrides (1 query)- insert_override_batch(pending_overrides)- context.log.info(f"Inserted {len(pending_overrides)} overrides")--[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})-def fix_missing_person_overrides_job():- """Job to automatically fix missing person_id overrides for a team."""- fix_missing_person_overrides_op()diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex 34ed3ad5efd2..bc37b302b030 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -11,10 +11,8 @@ from posthog.dags import (deletes,drop_materialized_column,export_query_log_archive_to_s3,- fix_missing_person_overrides,fix_person_id_overrides,flag_evaluations_backfill,- orm_examples,part_breaker,person_overrides,person_pg_cleanup_drain,@@ -28,8 +26,6 @@ defs = dagster.Definitions(assets=[ch_examples.get_clickhouse_version,ch_examples.print_clickhouse_version,- orm_examples.process_pending_deletions,- orm_examples.pending_deletions,postgres_to_clickhouse_etl.organizations_in_clickhouse,postgres_to_clickhouse_etl.teams_in_clickhouse,postgres_to_clickhouse_etl.feature_flags_in_clickhouse,@@ -43,7 +39,6 @@ defs = dagster.Definitions(deletes.manual_deletes_job,export_query_log_archive_to_s3.export_query_log_archive_to_s3,backfill_materialized_column.backfill_materialized_column,- fix_missing_person_overrides.fix_missing_person_overrides_job,fix_person_id_overrides.fix_person_id_overrides_job,flag_evaluations_backfill.flag_evaluations_backfill_job,person_overrides.cleanup_orphaned_person_overrides_snapshot,diff --git a/posthog/dags/locations/ingestion.py b/posthog/dags/locations/ingestion.pyindex deb2cf018228..9f8dba5dcaa8 100644--- a/posthog/dags/locations/ingestion.py+++ b/posthog/dags/locations/ingestion.py@@ -1,16 +1,12 @@import dagsterfrom posthog.dags import (- delete_persons_from_trigger_log,detach_distinct_id,distinct_id_usage,ingestion_assets,person_property_reconciliation,- persondistinctids_without_person_cleanup,personhog_shadow_drift,personhog_shadow_lane,- persons_new_backfill,- persons_without_distinct_ids_cleanup,)from . import loggers, resources@@ -20,15 +16,11 @@ defs = dagster.Definitions(ingestion_assets.postgres_env_check,],jobs=[- delete_persons_from_trigger_log.delete_persons_from_trigger_log_job,detach_distinct_id.detach_distinct_id_job,distinct_id_usage.distinct_id_usage_monitoring,person_property_reconciliation.person_property_reconciliation_job,- persondistinctids_without_person_cleanup.persondistinctids_without_person_cleanup_job,personhog_shadow_drift.personhog_shadow_lane_stop_and_compare_job,personhog_shadow_lane.personhog_shadow_lane_start_job,- persons_new_backfill.persons_new_backfill_job,- persons_without_distinct_ids_cleanup.persons_without_distinct_ids_cleanup_job,],schedules=[distinct_id_usage.distinct_id_usage_monitoring_schedule,diff --git a/posthog/dags/orm_examples.py b/posthog/dags/orm_examples.pydeleted file mode 100644index b7e5eeb8fd8a..000000000000--- a/posthog/dags/orm_examples.py+++ /dev/null@@ -1,31 +0,0 @@-from django.db.models import Q--import dagster--from posthog.models.async_deletion import AsyncDeletion, DeletionType---def pending_deletions() -> list[AsyncDeletion]:- """- Asset that fetches pending async deletions from Django ORM.- """- pending_deletions = AsyncDeletion.objects.filter(- Q(deletion_type=DeletionType.Person) & Q(delete_verified_at__isnull=True)- ).all()-- return list(pending_deletions)--[email protected](deps=[pending_deletions])-def process_pending_deletions(pending_deletions: list[AsyncDeletion]) -> None:- """- Asset that prints out pending deletions.- """- if not pending_deletions:- print("No pending deletions found") # noqa- return-- print(f"Found {len(pending_deletions)} pending deletions:") # noqa- for deletion in pending_deletions:- print(f"- Deletion ID: {deletion.id}, Type: {deletion.deletion_type}, Created at: {deletion.created_at}") # noqadiff --git a/posthog/dags/owners.yaml b/posthog/dags/owners.yamlindex 2fcf36fc5623..ab44c8654ff1 100644--- a/posthog/dags/owners.yaml+++ b/posthog/dags/owners.yaml@@ -3,11 +3,9 @@ owners: []rules:- match:- '/detach_distinct_id.py'- - '/fix_missing_person_overrides.py'- '/fix_person_id_overrides.py'- '/person_property_reconciliation.py'- '/tests/test_person_property_reconciliation.py'- - '/tests/test_person_property_reconciliation_restore.py'owners: team-ingestion- match: '/sessions.py'owners: team-analytics-platformdiff --git a/posthog/dags/person_property_reconciliation_restore.py b/posthog/dags/person_property_reconciliation_restore.pydeleted file mode 100644index d26b19d5a1a4..000000000000--- a/posthog/dags/person_property_reconciliation_restore.py+++ /dev/null@@ -1,603 +0,0 @@-"""Dagster job for restoring person properties from backup table.--This job reads backup entries created by the reconciliation job and restores-person properties with configurable conflict resolution strategies.-"""--import json-import time-from typing import Any--from django.conf import settings--import dagster-import psycopg2-from dagster_k8s import k8s_job_executor--from posthog.clickhouse.cluster import ClickhouseCluster-from posthog.clickhouse.custom_metrics import MetricsClient-from posthog.dags.common import JobOwners-from posthog.dags.person_property_reconciliation import publish_person_to_kafka-from posthog.kafka_client.client import _KafkaProducer--executor_def = dagster.in_process_executor if settings.DEBUG else k8s_job_executor---def ensure_dict(value: Any) -> dict:- """Ensure a value is a dict, parsing from JSON string if needed."""- if value is None:- return {}- if isinstance(value, dict):- return value- if isinstance(value, str):- return json.loads(value)- return {}---class PersonPropertyRestoreConfig(dagster.Config):- """Configuration for the person property restore job."""-- job_id: str # Which backup job to restore from- team_ids: list[int] | None = None # Optional: filter to specific teams- person_ids: list[int] | None = None # Optional: filter to specific persons- conflict_resolution: str = "keep_newer" # "keep_newer", "restore_wins", "full_overwrite"- dry_run: bool = False # Log without applying- backup_batch_size: int = 1000 # Batch size for fetching backup entries---def fetch_backup_entries(- cursor,- job_id: str,- team_ids: list[int] | None = None,- person_ids: list[int] | None = None,-) -> list[dict]:- """Fetch backup entries for restore (non-paginated, for backward compatibility)."""- entries = []- for batch in fetch_backup_entries_paginated(cursor, job_id, team_ids, person_ids):- entries.extend(batch)- return entries---def fetch_backup_entries_paginated(- cursor,- job_id: str,- team_ids: list[int] | None = None,- person_ids: list[int] | None = None,- batch_size: int = 1000,-):- """- Fetch backup entries using keyset pagination.-- Yields batches of entries ordered by (team_id, person_id).- """- base_query = """- SELECT- job_id, team_id, person_id, uuid::text,- properties, properties_last_updated_at, properties_last_operation, version,- is_identified, created_at, is_user_id,- properties_after, properties_last_updated_at_after, properties_last_operation_after, version_after- FROM posthog_person_reconciliation_backup- WHERE job_id = %s- """-- last_team_id: int | None = None- last_person_id: int | None = None-- while True:- query = base_query- params: list[Any] = [job_id]-- if team_ids:- query += " AND team_id = ANY(%s)"- params.append(team_ids)-- if person_ids:- query += " AND person_id = ANY(%s)"- params.append(person_ids)-- # Keyset pagination: fetch records after the last (team_id, person_id)- if last_team_id is not None and last_person_id is not None:- query += " AND (team_id, person_id) > (%s, %s)"- params.extend([last_team_id, last_person_id])-- query += " ORDER BY team_id, person_id LIMIT %s"- params.append(batch_size)-- cursor.execute(query, params)- rows = cursor.fetchall()-- if not rows:- break-- columns = [desc[0] for desc in cursor.description]- batch = [dict(zip(columns, row)) for row in rows]-- # Update cursor position for next iteration- last_row = batch[-1]- last_team_id = last_row["team_id"]- last_person_id = last_row["person_id"]-- yield batch-- # If we got fewer rows than batch_size, we've reached the end- if len(rows) < batch_size:- break---def fetch_person_by_id(cursor, team_id: int, person_id: int) -> dict | None:- """Fetch current person state by id."""- cursor.execute(- """- SELECT- id,- uuid::text,- properties,- properties_last_updated_at,- properties_last_operation,- version,- is_identified,- created_at,- is_user_id- FROM posthog_person- WHERE team_id = %s AND id = %s AND is_deleted = false- """,- (team_id, person_id),- )- row = cursor.fetchone()- if not row:- return None- columns = [desc[0] for desc in cursor.description]- result = dict(zip(columns, row))- # Ensure JSONB fields are parsed (handles both RealDictCursor and regular cursors)- result["properties"] = ensure_dict(result.get("properties"))- result["properties_last_updated_at"] = ensure_dict(result.get("properties_last_updated_at"))- result["properties_last_operation"] = ensure_dict(result.get("properties_last_operation"))- return result---def fetch_persons_by_ids(cursor, team_id: int, person_ids: list[int]) -> dict[int, dict]:- """Batch fetch current person states by ids. Returns dict mapping person_id -> person data."""- if not person_ids:- return {}-- cursor.execute(- """- SELECT- id,- uuid::text,- properties,- properties_last_updated_at,- properties_last_operation,- version,- is_identified,- created_at,- is_user_id- FROM posthog_person- WHERE team_id = %s AND id = ANY(%s) AND is_deleted = false- """,- (team_id, person_ids),- )- rows = cursor.fetchall()- if not rows:- return {}-- columns = [desc[0] for desc in cursor.description]- result = {}- for row in rows:- person = dict(zip(columns, row))- person["properties"] = ensure_dict(person.get("properties"))- person["properties_last_updated_at"] = ensure_dict(person.get("properties_last_updated_at"))- person["properties_last_operation"] = ensure_dict(person.get("properties_last_operation"))- result[person["id"]] = person- return result---def compute_restore_diff(- current_person: dict,- backup_before: dict,- backup_after: dict,- conflict_resolution: str,-) -> dict | None:- """- Compute what properties to restore.-- Args:- current_person: Current state from posthog_person table- backup_before: "Before" state from backup (what we want to restore TO)- backup_after: "After" state from backup (what reconciliation changed it TO)- conflict_resolution: How to handle conflicts- - "full_overwrite": Complete replacement with backup's before state- - "restore_wins": Restore all backed-up properties, preserve new properties added after backup- - "keep_newer": Only restore properties unchanged since backup-- Returns:- Dict with updated properties, or None if no changes needed.- """- current_props = current_person.get("properties") or {}- backup_before_props = backup_before.get("properties") or {}- backup_after_props = backup_after.get("properties") or {}-- if conflict_resolution == "full_overwrite":- if current_props == backup_before_props:- return None- return {- "properties": dict(backup_before_props),- "properties_last_updated_at": dict(backup_before.get("properties_last_updated_at") or {}),- "properties_last_operation": dict(backup_before.get("properties_last_operation") or {}),- }-- result_properties = dict(current_props)- result_last_updated_at = dict(current_person.get("properties_last_updated_at") or {})- result_last_operation = dict(current_person.get("properties_last_operation") or {})- changes_made = False-- backup_before_last_updated_at = backup_before.get("properties_last_updated_at") or {}- backup_before_last_operation = backup_before.get("properties_last_operation") or {}-- for key, before_value in backup_before_props.items():- current_value = current_props.get(key)- after_value = backup_after_props.get(key)-- if conflict_resolution == "restore_wins":- if current_value != before_value:- result_properties[key] = before_value- # Restore metadata to backup state (set if present, remove if not)- if key in backup_before_last_updated_at:- result_last_updated_at[key] = backup_before_last_updated_at[key]- else:- result_last_updated_at.pop(key, None)- if key in backup_before_last_operation:- result_last_operation[key] = backup_before_last_operation[key]- else:- result_last_operation.pop(key, None)- changes_made = True-- elif conflict_resolution == "keep_newer":- if current_value == after_value and current_value != before_value:- result_properties[key] = before_value- # Restore metadata to backup state (set if present, remove if not)- if key in backup_before_last_updated_at:- result_last_updated_at[key] = backup_before_last_updated_at[key]- else:- result_last_updated_at.pop(key, None)- if key in backup_before_last_operation:- result_last_operation[key] = backup_before_last_operation[key]- else:- result_last_operation.pop(key, None)- changes_made = True-- if not changes_made:- return None-- return {- "properties": result_properties,- "properties_last_updated_at": result_last_updated_at,- "properties_last_operation": result_last_operation,- }---def restore_person_with_version_check(- cursor,- team_id: int,- person_id: int,- person_uuid: str,- backup_entry: dict,- conflict_resolution: str,- dry_run: bool = False,- max_retries: int = 3,- prefetched_person: dict | None = None,-) -> tuple[bool, dict | None]:- """- Restore a person's properties with optimistic locking.-- Args:- cursor: Database cursor- team_id: Team ID- person_id: Person ID (from backup)- person_uuid: Person UUID- backup_entry: Backup entry with before/after state- conflict_resolution: "keep_newer", "restore_wins", or "full_overwrite"- dry_run: If True, don't actually write the UPDATE- max_retries: Maximum retry attempts on version mismatch- prefetched_person: Optional pre-fetched person data (used on first attempt)-- Returns:- Tuple of (success: bool, updated_person_data: dict | None)- updated_person_data contains the final state for Kafka publishing- """- backup_before = {- "properties": ensure_dict(backup_entry.get("properties")),- "properties_last_updated_at": ensure_dict(backup_entry.get("properties_last_updated_at")),- "properties_last_operation": ensure_dict(backup_entry.get("properties_last_operation")),- }- backup_after = {- "properties": ensure_dict(backup_entry.get("properties_after")),- "properties_last_updated_at": ensure_dict(backup_entry.get("properties_last_updated_at_after")),- "properties_last_operation": ensure_dict(backup_entry.get("properties_last_operation_after")),- }-- for attempt in range(max_retries):- # Use prefetched person on first attempt, fetch fresh on retries- person: dict | None- if attempt == 0 and prefetched_person is not None:- person = prefetched_person- else:- person = fetch_person_by_id(cursor, team_id, person_id)- if not person:- return False, None-- current_version = person.get("version") or 0-- update = compute_restore_diff(person, backup_before, backup_after, conflict_resolution)- if not update:- return True, None-- if dry_run:- return True, None-- cursor.execute(- """- UPDATE posthog_person SET- properties = %s,- properties_last_updated_at = %s,- properties_last_operation = %s,- version = %s- WHERE team_id = %s AND id = %s AND version = %s- RETURNING uuid- """,- (- json.dumps(update["properties"]),- json.dumps(update["properties_last_updated_at"]),- json.dumps(update["properties_last_operation"]),- current_version + 1,- team_id,- person_id,- current_version,- ),- )-- if cursor.rowcount > 0:- return (- True,- {- "id": person_uuid,- "team_id": team_id,- "properties": update["properties"],- "is_identified": person.get("is_identified", False),- "is_deleted": 0,- "created_at": person.get("created_at"),- "version": current_version + 1,- },- )-- return False, None--[email protected](out=dagster.DynamicOut(list))-def get_backup_entries_by_team(- context: dagster.OpExecutionContext,- config: PersonPropertyRestoreConfig,- persons_database: dagster.ResourceParam[psycopg2.extensions.connection],-):- """- Query backup table and yield entries grouped by team.-- Uses keyset pagination to stream entries without loading all into memory.- Yields one DynamicOutput per team with all entries for that team.- """- context.log.info(f"Fetching backup entries for job_id: {config.job_id}")-- total_entries = 0- teams_seen: set[int] = set()- current_team_id: int | None = None- current_team_entries: list[dict] = []-- with persons_database.cursor() as cursor:- for batch in fetch_backup_entries_paginated(- cursor, config.job_id, config.team_ids, config.person_ids, batch_size=config.backup_batch_size- ):- for entry in batch:- team_id = entry["team_id"]-- # If we've moved to a new team, yield the previous team's entries- if current_team_id is not None and team_id != current_team_id:- context.log.info(f"Yielding {len(current_team_entries)} entries for team_id={current_team_id}")- yield dagster.DynamicOutput(- value=current_team_entries,- mapping_key=f"team_{current_team_id}",- )- teams_seen.add(current_team_id)- current_team_entries = []-- current_team_id = team_id- current_team_entries.append(entry)- total_entries += 1-- # Yield the last team's entries- if current_team_entries and current_team_id is not None:- context.log.info(f"Yielding {len(current_team_entries)} entries for team_id={current_team_id}")- yield dagster.DynamicOutput(- value=current_team_entries,- mapping_key=f"team_{current_team_id}",- )- teams_seen.add(current_team_id)-- context.log.info(f"Completed: found {total_entries} backup entries across {len(teams_seen)} teams")---def restore_team_chunk(- context: dagster.OpExecutionContext,- config: PersonPropertyRestoreConfig,- chunk: list[dict],- persons_database: dagster.ResourceParam[psycopg2.extensions.connection],- cluster: dagster.ResourceParam[ClickhouseCluster],- kafka_producer: dagster.ResourceParam[_KafkaProducer],-) -> dict[str, Any]:- """Restore person properties for all backup entries in a team chunk."""- if not chunk:- return {"team_id": 0, "persons_processed": 0, "persons_restored": 0, "persons_skipped": 0}-- team_id = chunk[0]["team_id"]- job_name = context.run.job_name- chunk_id = f"team_{team_id}"- metrics_client = MetricsClient(cluster)-- context.log.info(- f"Starting restore for team_id={team_id}, entries={len(chunk)}, "- f"conflict_resolution={config.conflict_resolution}"- )-- total_processed = 0- total_restored = 0- total_skipped = 0-- try:- start_time = time.time()-- with persons_database.cursor() as cursor:- cursor.execute("SET application_name = 'person_property_restore'")- cursor.execute("SET lock_timeout = '5s'")- cursor.execute("SET statement_timeout = '30min'")- cursor.execute("SET synchronous_commit = off")-- # Batch fetch all persons for this chunk- person_ids = [entry["person_id"] for entry in chunk]- prefetched_persons = fetch_persons_by_ids(cursor, team_id, person_ids)- context.log.info(f"Batch fetched {len(prefetched_persons)} persons for team_id={team_id}")-- persons_to_publish = []-- for backup_entry in chunk:- person_id = backup_entry["person_id"]- person_uuid = backup_entry["uuid"]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team_id,- person_id=person_id,- person_uuid=person_uuid,- backup_entry=backup_entry,- conflict_resolution=config.conflict_resolution,- dry_run=config.dry_run,- prefetched_person=prefetched_persons.get(person_id),- )-- if not success:- context.log.warning(f"Failed to restore person after retries: {person_id}")- total_skipped += 1- elif person_data:- persons_to_publish.append(person_data)- total_restored += 1- else:- total_skipped += 1-- total_processed += 1-- if persons_to_publish and not config.dry_run:- persons_database.commit()-- for person_data in persons_to_publish:- try:- publish_person_to_kafka(person_data, kafka_producer)- except Exception as kafka_error:- context.log.warning(- f"Failed to publish person to Kafka: {person_data['id']}, error: {kafka_error}"- )- try:- kafka_producer.flush()- except Exception as flush_error:- context.log.warning(f"Failed to flush Kafka producer: {flush_error}")-- context.log.info(f"Restored {len(persons_to_publish)} persons for team_id={team_id}")- elif persons_to_publish and config.dry_run:- context.log.info(f"[DRY RUN] Would restore {len(persons_to_publish)} persons for team_id={team_id}")-- duration = time.time() - start_time- try:- metrics_client.increment(- "person_property_restore_persons_processed_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(total_processed),- ).result()- metrics_client.increment(- "person_property_restore_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=duration,- ).result()- except Exception:- pass-- except Exception as e:- error_msg = f"Error for team_id={team_id}: {e}"- context.log.exception(error_msg)-- try:- metrics_client.increment(- "person_property_restore_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "error"},- value=1.0,- ).result()- except Exception:- pass-- raise dagster.Failure(- description=error_msg,- metadata={- "team_id": dagster.MetadataValue.int(team_id),- "error_message": dagster.MetadataValue.text(str(e)),- "persons_processed_before_failure": dagster.MetadataValue.int(total_processed),- },- ) from e-- context.log.info(- f"Completed team_id={team_id}: processed={total_processed}, restored={total_restored}, skipped={total_skipped}"- )-- try:- metrics_client.increment(- "person_property_restore_persons_restored_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(total_restored),- ).result()- metrics_client.increment(- "person_property_restore_persons_skipped_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(total_skipped),- ).result()- except Exception:- pass-- context.add_output_metadata(- {- "team_id": dagster.MetadataValue.int(team_id),- "persons_processed": dagster.MetadataValue.int(total_processed),- "persons_restored": dagster.MetadataValue.int(total_restored),- "persons_skipped": dagster.MetadataValue.int(total_skipped),- }- )-- return {- "team_id": team_id,- "persons_processed": total_processed,- "persons_restored": total_restored,- "persons_skipped": total_skipped,- }--- tags={"owner": JobOwners.TEAM_INGESTION.value},- executor_def=executor_def,-)-def person_property_reconciliation_restore_from_backup():- """- Job to restore person properties from backup table.-- This job reads backup entries created by the reconciliation job and- restores person properties. Conflict resolution options:- - full_overwrite: Complete overwrite with backup's "before" state- - restore_wins: Restore all backed-up properties, preserve new ones added after backup- - keep_newer: Only restore properties unchanged since backup- """- team_chunks = get_backup_entries_by_team()- team_chunks.map(restore_team_chunk)diff --git a/posthog/dags/persondistinctids_without_person_cleanup.py b/posthog/dags/persondistinctids_without_person_cleanup.pydeleted file mode 100644index 3b5eb19ce2fd..000000000000--- a/posthog/dags/persondistinctids_without_person_cleanup.py+++ /dev/null@@ -1,525 +0,0 @@-"""Dagster job for deleting posthog_persondistinctid rows that have no associated posthog_person_new rows."""--import os-import time-from typing import Any--import dagster-import psycopg2-import psycopg2.errors-from dagster_k8s import k8s_job_executor--from posthog.clickhouse.cluster import ClickhouseCluster-from posthog.clickhouse.custom_metrics import MetricsClient-from posthog.dags.common import JobOwners--MAX_RETRY_ATTEMPTS = 5---class PersonsDistinctIdsNoPersonCleanupConfig(dagster.Config):- """Configuration for the persondistinctids without person cleanup job."""-- chunk_size: int = 10_000_000 # persondistinctid rows per chunk worker to scan across- batch_size: int = (- 5000 # persondistinctid rows to scan for missing parent person row & delete in a single transaction- )- persons_table: str = "posthog_person_new" # set safe default we can override after name swap!- max_id: int | None = None # Optional override for max ID to resume from partial state- min_id: int | None = None # Optional override for min ID to resume from partial state---def get_id_range_for_pdwp(- context: dagster.OpExecutionContext,- config: PersonsDistinctIdsNoPersonCleanupConfig,- database: dagster.ResourceParam[psycopg2.extensions.connection],-) -> tuple[int, int]:- """- Query source database for MIN(id) and MAX(id) from posthog_persondistinctid- table. If min_id and max_id are provided in config, uses that instead of querying.- Returns tuple (min_id, max_id).- """- with database.cursor() as cursor:- # Use config min_id if provided, otherwise query database- if config.min_id is not None:- min_id = config.min_id- context.log.info(f"Using configured min_id override: {min_id}")- else:- min_query = f"SELECT MIN(id) as min_id FROM posthog_persondistinctid"- context.log.info(f"Querying min ID: {min_query}")- cursor.execute(min_query)- min_result = cursor.fetchone()-- if min_result is None or min_result["min_id"] is None:- context.log.exception("Source table has no valid min ID")- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure("Source table has no valid min ID")-- min_id = int(min_result["min_id"])-- # Use config max_id if provided, otherwise query database- if config.max_id is not None:- max_id = config.max_id- context.log.info(f"Using configured max_id override: {max_id}")- else:- max_query = f"SELECT MAX(id) as max_id FROM posthog_persondistinctid"- context.log.info(f"Querying max ID: {max_query}")- cursor.execute(max_query)- max_result = cursor.fetchone()-- if max_result is None or max_result["max_id"] is None:- context.log.exception(f"{config.persons_table} table has no valid max ID")- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure(f"{config.persons_table} table has no valid max ID")-- max_id = int(max_result["max_id"])-- # Validate that max_id >= min_id- if max_id < min_id:- error_msg = f"Invalid ID range: max_id ({max_id}) < min_id ({min_id})"- context.log.error(error_msg)- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure(error_msg)-- context.log.info(f"ID range: min={min_id}, max={max_id}, total_ids={max_id - min_id + 1}")- context.add_output_metadata(- {- "min_id": dagster.MetadataValue.int(min_id),- "min_id_source": dagster.MetadataValue.text("config" if config.min_id is not None else "database"),- "max_id": dagster.MetadataValue.int(max_id),- "max_id_source": dagster.MetadataValue.text("config" if config.max_id is not None else "database"),- "total_ids": dagster.MetadataValue.int(max_id - min_id + 1),- }- )-- return (min_id, max_id)--[email protected](out=dagster.DynamicOut(tuple[int, int]))-def create_chunks_for_pdwp(- context: dagster.OpExecutionContext,- config: PersonsDistinctIdsNoPersonCleanupConfig,- id_range: tuple[int, int],-):- """- Divide ID space into chunks of chunk_size.- Yields DynamicOutput for each chunk in reverse order (highest IDs first, lowest IDs last).- This ensures that if the job fails partway through, the final chunk to process will be- the one starting at the source table's min_id.- """- min_id, max_id = id_range- chunk_size = config.chunk_size-- # First, collect all chunks- chunks = []- chunk_min = min_id- chunk_num = 0-- while chunk_min <= max_id:- chunk_max = min(chunk_min + chunk_size - 1, max_id)- chunks.append((chunk_min, chunk_max, chunk_num))- chunk_min = chunk_max + 1- chunk_num += 1-- context.log.info(f"Created {chunk_num} chunks total")-- # Yield chunks in reverse order (highest IDs first)- for chunk_min, chunk_max, chunk_num in reversed(chunks):- chunk_key = f"chunk_{chunk_min}_{chunk_max}"- context.log.info(f"Yielding chunk {chunk_num}: {chunk_min} to {chunk_max}")- yield dagster.DynamicOutput(- value=(chunk_min, chunk_max),- mapping_key=chunk_key,- )---def scan_delete_chunk_for_pdwp(- context: dagster.OpExecutionContext,- config: PersonsDistinctIdsNoPersonCleanupConfig,- chunk: tuple[int, int],- database: dagster.ResourceParam[psycopg2.extensions.connection],- cluster: dagster.ResourceParam[ClickhouseCluster],-) -> dict[str, Any]:- """- Scan posthog_person_new table for records that have no associated posthog_persondistinctid row,- and deletes the corresponding posthog_person_new row.- Processes in batches of batch_size records.- """- chunk_min, chunk_max = chunk- batch_size = config.batch_size- chunk_id = f"chunk_{chunk_min}_{chunk_max}"- job_name = context.run.job_name-- # Initialize metrics client- metrics_client = MetricsClient(cluster)-- context.log.info(f"Starting chunk scan and delete for ID range: {chunk_min} to {chunk_max}")-- total_records_deleted = 0- batch_start_id = chunk_min- failed_batch_start_id: int | None = None-- # Accumulate metrics locally, publish every 100 batches- METRIC_PUBLISH_INTERVAL = 100- batch_counter = 0- accumulated_records_attempted = 0- accumulated_records_found = 0- accumulated_records_deleted = 0- accumulated_batches_scanned = 0- accumulated_batch_duration = 0.0-- try:- with database.cursor() as cursor:- # Set session-level settings once for the entire chunk- cursor.execute("SET application_name = 'delete_personsdistinctids_with_no_person'")- cursor.execute("SET lock_timeout = '5s'")- cursor.execute("SET statement_timeout = '30min'")- cursor.execute("SET work_mem = '512MB'")- cursor.execute("SET temp_buffers = '512MB'")- cursor.execute("SET max_parallel_workers_per_gather = 2")- cursor.execute("SET max_parallel_maintenance_workers = 2")- cursor.execute("SET synchronous_commit = off")-- retry_attempt = 0- while batch_start_id <= chunk_max:- try:- # Track batch start time for duration metric- batch_start_time = time.time()-- # Calculate batch end ID- batch_end_id = min(batch_start_id + batch_size, chunk_max)-- # Track records attempted - this is also our exit condition- records_scanned = batch_end_id - batch_start_id- if records_scanned <= 0:- break-- # Begin transaction (settings already applied at session level)- cursor.execute("BEGIN")-- # Delete orphaned posthog_persondistinctid rows and return their IDs- # Using DELETE...RETURNING for efficiency (single query instead of scan + delete)- delete_query = f"""-DELETE FROM posthog_persondistinctid pd-WHERE pd.id >= %s AND pd.id <= %s- AND NOT EXISTS (- SELECT 1- FROM {config.persons_table} AS p- WHERE p.team_id = pd.team_id- AND p.id = pd.person_id- )-RETURNING pd.id-"""- cursor.execute(delete_query, (batch_start_id, batch_end_id))- deleted_rows = cursor.fetchall()- records_deleted = len(deleted_rows)- records_found = records_deleted # With DELETE...RETURNING, found == deleted-- # Commit the transaction- cursor.execute("COMMIT")-- # Track batch duration- batch_duration_seconds = time.time() - batch_start_time-- # Accumulate metrics locally- accumulated_records_attempted += records_scanned + 1- accumulated_records_found += records_found- accumulated_records_deleted += records_deleted- accumulated_batches_scanned += 1- accumulated_batch_duration += batch_duration_seconds- batch_counter += 1- total_records_deleted += records_deleted-- # Publish accumulated metrics every METRIC_PUBLISH_INTERVAL batches- if batch_counter >= METRIC_PUBLISH_INTERVAL:- try:- metrics_client.increment(- "distinct_ids_without_person_records_attempted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_attempted),- ).result()- except Exception:- pass-- try:- metrics_client.increment(- "distinct_ids_without_person_records_found_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_found),- ).result()- except Exception:- pass-- try:- metrics_client.increment(- "distinct_ids_without_person_records_deleted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_deleted),- ).result()- except Exception:- pass-- try:- metrics_client.increment(- "distinct_ids_without_person_batches_scanned_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_batches_scanned),- ).result()- except Exception:- pass-- try:- metrics_client.increment(- "distinct_ids_without_person_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=accumulated_batch_duration,- ).result()- except Exception:- pass-- # Reset accumulators- accumulated_records_attempted = 0- accumulated_records_found = 0- accumulated_records_deleted = 0- accumulated_batches_scanned = 0- accumulated_batch_duration = 0.0- batch_counter = 0-- context.log.info(- f"Deleted batch: {records_deleted} of {records_found} records "- f"(chunk {chunk_min}-{chunk_max}, batch ID range {batch_start_id} to {batch_end_id})"- )-- # Update batch_start_id for next iteration- batch_start_id = batch_end_id + 1- retry_attempt = 0-- except Exception as batch_error:- # Rollback transaction on error- try:- cursor.execute("ROLLBACK")- except Exception as rollback_error:- context.log.exception(- f"Failed to rollback transaction for batch starting at ID {batch_start_id}"- f"in chunk {chunk_min}-{chunk_max}: {str(rollback_error)}"- )- pass # Ignore rollback errors-- # Check if error is a serialization failure, pause and retry if so- serialization_failure_class = getattr(psycopg2.errors, "SerializationFailure", None)- is_serialization_failure = (- serialization_failure_class is not None and isinstance(batch_error, serialization_failure_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40001")- if is_serialization_failure:- error_msg = (- f"Serialization failure detected for batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}. Error is: {batch_error}. "- "This is expected due to concurrent transactions. "- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch: attempt {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Check if error is a deadlock, pause and retry if so- deadlock_detected_class = getattr(psycopg2.errors, "DeadlockDetected", None)- is_deadlock = (- deadlock_detected_class is not None and isinstance(batch_error, deadlock_detected_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40P01")- if is_deadlock:- error_msg = (- f"Deadlock detected for batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}. Error is: {batch_error}. "- "This is expected due to concurrent transactions. "- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch: attempt {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Handle unexpected errors by bubbling up to dagster.Failure- failed_batch_start_id = batch_start_id- error_msg = (- f"Failed to scan and delete rows in batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}: {str(batch_error)}"- )- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "distinct_ids_without_person_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "batch_scan_delete_failed"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.text("N/A"),- "error_message": dagster.MetadataValue.text(str(batch_error)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from batch_error-- except dagster.Failure:- # Re-raise Dagster failures as-is (they already have metadata and metrics)- raise- except Exception as e:- # Flush any remaining accumulated metrics before raising- if batch_counter > 0:- try:- metrics_client.increment(- "distinct_ids_without_person_records_attempted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_attempted),- ).result()- metrics_client.increment(- "distinct_ids_without_person_records_found_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_found),- ).result()- metrics_client.increment(- "distinct_ids_without_person_records_deleted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_deleted),- ).result()- metrics_client.increment(- "distinct_ids_without_person_batches_scanned_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_batches_scanned),- ).result()- metrics_client.increment(- "distinct_ids_without_person_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=accumulated_batch_duration,- ).result()- except Exception:- pass-- # Catch any other unexpected errors- error_msg = f"Unexpected error scanning and deleting from chunk {chunk_min}-{chunk_max}: {str(e)}"- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "distinct_ids_without_person_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "unexpected_scan_delete_error"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.int(batch_start_id),- "error_message": dagster.MetadataValue.text(str(e)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from e-- context.log.info(f"Completed chunk {chunk_min}-{chunk_max}: deleted {total_records_deleted} records")-- # Flush any remaining accumulated metrics at end of chunk- if batch_counter > 0:- try:- metrics_client.increment(- "distinct_ids_without_person_records_attempted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_attempted),- ).result()- metrics_client.increment(- "distinct_ids_without_person_records_found_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_found),- ).result()- metrics_client.increment(- "distinct_ids_without_person_records_deleted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_deleted),- ).result()- metrics_client.increment(- "distinct_ids_without_person_batches_scanned_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_batches_scanned),- ).result()- metrics_client.increment(- "distinct_ids_without_person_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=accumulated_batch_duration,- ).result()- except Exception:- pass-- # Emit metric for chunk completion- run_id = context.run.run_id- try:- metrics_client.increment(- "distinct_ids_without_person_chunks_completed_total",- labels={"job_name": job_name, "run_id": run_id, "chunk_id": chunk_id},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- context.add_output_metadata(- {- "chunk_min": dagster.MetadataValue.int(chunk_min),- "chunk_max": dagster.MetadataValue.int(chunk_max),- "records_deleted": dagster.MetadataValue.int(total_records_deleted),- }- )-- return {- "chunk_min": chunk_min,- "chunk_max": chunk_max,- "records_deleted": total_records_deleted,- }---def postgres_env_check(context: dagster.AssetExecutionContext) -> None:- """- Simple asset that prints PostgreSQL environment variables being used.- Useful for debugging connection configuration.- """- env_vars = {- "POSTGRES_HOST": os.getenv("POSTGRES_HOST", "not set"),- "POSTGRES_PORT": os.getenv("POSTGRES_PORT", "not set"),- "POSTGRES_DATABASE": os.getenv("POSTGRES_DATABASE", "not set"),- "POSTGRES_USER": os.getenv("POSTGRES_USER", "not set"),- "POSTGRES_PASSWORD": "***" if os.getenv("POSTGRES_PASSWORD") else "not set",- }-- context.log.info("PostgreSQL environment variables:")- for key, value in env_vars.items():- context.log.info(f" {key}: {value}")--- tags={"owner": JobOwners.TEAM_INGESTION.value},- executor_def=k8s_job_executor,-)-def persondistinctids_without_person_cleanup_job():- """- Scan posthog_persondistinctid table for records that have no associated posthog_person_new row,- and deletes the corresponding posthog_persondistinctid rows that carry the missing person_id.- Divides the ID space into chunks and processes them in parallel.- """- id_range = get_id_range_for_pdwp()- chunks = create_chunks_for_pdwp(id_range)- chunks.map(scan_delete_chunk_for_pdwp)diff --git a/posthog/dags/persons_new_backfill.py b/posthog/dags/persons_new_backfill.pydeleted file mode 100644index 4d19b99ac7f9..000000000000--- a/posthog/dags/persons_new_backfill.py+++ /dev/null@@ -1,404 +0,0 @@-"""Dagster job for backfilling posthog_persons data from source to destination Postgres database."""--import os-import time-from typing import Any--import dagster-import psycopg2-import psycopg2.errors-from dagster_k8s import k8s_job_executor--from posthog.clickhouse.cluster import ClickhouseCluster-from posthog.clickhouse.custom_metrics import MetricsClient-from posthog.dags.common import JobOwners---class PersonsNewBackfillConfig(dagster.Config):- """Configuration for the persons new backfill job."""-- chunk_size: int = 1_000_000 # ID range per chunk- batch_size: int = 100_000 # Records per batch insert- source_table: str = "posthog_persons"- destination_table: str = "posthog_persons_new"- min_id: int | None = None # Optional override for min ID to resume from partial state- max_id: int | None = None # Optional override for max ID to resume from partial state---def get_id_range_for_pnb(- context: dagster.OpExecutionContext,- config: PersonsNewBackfillConfig,- database: dagster.ResourceParam[psycopg2.extensions.connection],-) -> tuple[int, int]:- """- Query source database for MIN(id) and optionally MAX(id) from posthog_persons table.- If max_id is provided in config, uses that instead of querying.- Returns tuple (min_id, max_id).- """- with database.cursor() as cursor:- # Use config min_id if provided, otherwise query database- if config.min_id is not None:- min_id = config.min_id- context.log.info(f"Using configured min_id override: {config.min_id}")- else:- # Always query for min_id- min_query = f"SELECT MIN(id) as min_id FROM {config.source_table}"- context.log.info(f"Querying min ID: {min_query}")- cursor.execute(min_query)- min_result = cursor.fetchone()-- if min_result is None or min_result["min_id"] is None:- context.log.exception("Source table has no valid min ID")- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure("Source table has no valid min ID")-- min_id = int(min_result["min_id"])-- # Use config max_id if provided, otherwise query database- if config.max_id is not None:- max_id = config.max_id- context.log.info(f"Using configured max_id override: {max_id}")- else:- max_query = f"SELECT MAX(id) as max_id FROM {config.source_table}"- context.log.info(f"Querying max ID: {max_query}")- cursor.execute(max_query)- max_result = cursor.fetchone()-- if max_result is None or max_result["max_id"] is None:- context.log.exception("Source table has no valid max ID")- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure("Source table has no valid max ID")-- max_id = int(max_result["max_id"])-- # Validate that max_id >= min_id- if max_id < min_id:- error_msg = f"Invalid ID range: max_id ({max_id}) < min_id ({min_id})"- context.log.error(error_msg)- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure(error_msg)-- context.log.info(f"ID range: min={min_id}, max={max_id}, total_ids={max_id - min_id + 1}")- context.add_output_metadata(- {- "min_id": dagster.MetadataValue.int(min_id),- "min_id_source": dagster.MetadataValue.text("config" if config.min_id is not None else "database"),- "max_id": dagster.MetadataValue.int(max_id),- "max_id_source": dagster.MetadataValue.text("config" if config.max_id is not None else "database"),- "total_ids": dagster.MetadataValue.int(max_id - min_id + 1),- }- )-- return (min_id, max_id)--[email protected](out=dagster.DynamicOut(tuple[int, int]))-def create_chunks_for_pnb(- context: dagster.OpExecutionContext,- config: PersonsNewBackfillConfig,- id_range: tuple[int, int],-):- """- Divide ID space into chunks of chunk_size.- Yields DynamicOutput for each chunk in reverse order (highest IDs first, lowest IDs last).- This ensures that if the job fails partway through, the final chunk to process will be- the one starting at the source table's min_id.- """- min_id, max_id = id_range- chunk_size = config.chunk_size-- # First, collect all chunks- chunks = []- chunk_min = min_id- chunk_num = 0-- while chunk_min <= max_id:- chunk_max = min(chunk_min + chunk_size - 1, max_id)- chunks.append((chunk_min, chunk_max, chunk_num))- chunk_min = chunk_max + 1- chunk_num += 1-- context.log.info(f"Created {chunk_num} chunks total")-- # Yield chunks in reverse order (highest IDs first)- for chunk_min, chunk_max, chunk_num in reversed(chunks):- chunk_key = f"chunk_{chunk_min}_{chunk_max}"- context.log.info(f"Yielding chunk {chunk_num}: {chunk_min} to {chunk_max}")- yield dagster.DynamicOutput(- value=(chunk_min, chunk_max),- mapping_key=chunk_key,- )---def copy_chunk(- context: dagster.OpExecutionContext,- config: PersonsNewBackfillConfig,- chunk: tuple[int, int],- database: dagster.ResourceParam[psycopg2.extensions.connection],- cluster: dagster.ResourceParam[ClickhouseCluster],-) -> dict[str, Any]:- """- Copy a chunk of records from source to destination database.- Processes in batches of batch_size records.- """- chunk_min, chunk_max = chunk- batch_size = config.batch_size- source_table = config.source_table- destination_table = config.destination_table- chunk_id = f"chunk_{chunk_min}_{chunk_max}"- job_name = context.run.job_name-- # Initialize metrics client- metrics_client = MetricsClient(cluster)-- context.log.info(f"Starting chunk copy: {chunk_min} to {chunk_max}")-- total_records_copied = 0- batch_start_id = chunk_min- failed_batch_start_id: int | None = None-- try:- with database.cursor() as cursor:- # Set session-level settings once for the entire chunk- cursor.execute("SET application_name = 'backfill_posthog_persons_to_posthog_persons_new'")- cursor.execute("SET lock_timeout = '5s'")- cursor.execute("SET statement_timeout = '30min'")- cursor.execute("SET maintenance_work_mem = '12GB'")- cursor.execute("SET work_mem = '512MB'")- cursor.execute("SET temp_buffers = '512MB'")- cursor.execute("SET max_parallel_workers_per_gather = 2")- cursor.execute("SET max_parallel_maintenance_workers = 2")- cursor.execute("SET synchronous_commit = off")-- retry_attempt = 0- while batch_start_id <= chunk_max:- try:- # Track batch start time for duration metric- batch_start_time = time.time()-- # Calculate batch end ID- batch_end_id = min(batch_start_id + batch_size, chunk_max)-- # Track records attempted - this is also our exit condition- records_attempted = batch_end_id - batch_start_id- if records_attempted <= 0:- break- # Begin transaction (settings already applied at session level)- cursor.execute("BEGIN")-- # Execute INSERT INTO ... SELECT with NOT EXISTS check- insert_query = f"""-INSERT INTO {destination_table}-SELECT s.*-FROM {source_table} s-WHERE s.id >= %s AND s.id <= %s- AND NOT EXISTS (- SELECT 1- FROM {destination_table} d- WHERE d.team_id = s.team_id- AND d.id = s.id- )-ORDER BY s.id DESC-"""- cursor.execute(insert_query, (batch_start_id, batch_end_id))- records_inserted = cursor.rowcount-- # Commit the transaction- cursor.execute("COMMIT")-- try:- metrics_client.increment(- "persons_new_backfill_records_attempted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(records_attempted),- ).result()- except Exception:- pass # Don't fail on metrics error-- batch_duration_seconds = time.time() - batch_start_time-- try:- metrics_client.increment(- "persons_new_backfill_records_inserted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(records_inserted),- ).result()- except Exception:- pass # Don't fail on metrics error-- try:- metrics_client.increment(- "persons_new_backfill_batches_copied_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=1.0,- ).result()- except Exception:- pass- # Track batch duration metric (IV)- try:- metrics_client.increment(- "persons_new_backfill_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=batch_duration_seconds,- ).result()- except Exception:- pass-- total_records_copied += records_inserted-- context.log.info(- f"Copied batch: {records_inserted} records "- f"(chunk {chunk_min}-{chunk_max}, batch ID range {batch_start_id} to {batch_end_id})"- )-- # Update batch_start_id for next iteration- batch_start_id = batch_end_id + 1- retry_attempt = 0-- except Exception as batch_error:- # Rollback transaction on error- try:- cursor.execute("ROLLBACK")- except Exception as rollback_error:- context.log.exception(- f"Failed to rollback transaction for batch starting at ID {batch_start_id}"- f"in chunk {chunk_min}-{chunk_max}: {str(rollback_error)}"- )- pass # Ignore rollback errors-- # Check if error is a duplicate key violation, pause and retry if so- is_unique_violation = isinstance(batch_error, psycopg2.errors.UniqueViolation) or (- isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "23505"- )- if is_unique_violation:- error_msg = (- f"Duplicate key violation detected for batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}. Error is: {batch_error}. "- "This is expected if records already exist in destination table. "- )- context.log.warning(error_msg)- if retry_attempt < 3:- retry_attempt += 1- context.log.info(f"Retrying batch {retry_attempt} of 3...")- time.sleep(1)- continue-- failed_batch_start_id = batch_start_id- error_msg = (- f"Failed to copy batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}: {str(batch_error)}"- )- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "persons_new_backfill_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "batch_copy_failed"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.text("N/A"),- "error_message": dagster.MetadataValue.text(str(batch_error)),- "records_copied_before_failure": dagster.MetadataValue.int(total_records_copied),- },- ) from batch_error-- except dagster.Failure:- # Re-raise Dagster failures as-is (they already have metadata and metrics)- raise- except Exception as e:- # Catch any other unexpected errors- error_msg = f"Unexpected error copying chunk {chunk_min}-{chunk_max}: {str(e)}"- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "persons_new_backfill_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "unexpected_copy_error"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.int(batch_start_id),- "error_message": dagster.MetadataValue.text(str(e)),- "records_copied_before_failure": dagster.MetadataValue.int(total_records_copied),- },- ) from e-- context.log.info(f"Completed chunk {chunk_min}-{chunk_max}: copied {total_records_copied} records")-- # Emit metric for chunk completion- run_id = context.run.run_id- try:- metrics_client.increment(- "persons_new_backfill_chunks_completed_total",- labels={"job_name": job_name, "run_id": run_id, "chunk_id": chunk_id},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- context.add_output_metadata(- {- "chunk_min": dagster.MetadataValue.int(chunk_min),- "chunk_max": dagster.MetadataValue.int(chunk_max),- "records_copied": dagster.MetadataValue.int(total_records_copied),- }- )-- return {- "chunk_min": chunk_min,- "chunk_max": chunk_max,- "records_copied": total_records_copied,- }---def postgres_env_check(context: dagster.AssetExecutionContext) -> None:- """- Simple asset that prints PostgreSQL environment variables being used.- Useful for debugging connection configuration.- """- env_vars = {- "POSTGRES_HOST": os.getenv("POSTGRES_HOST", "not set"),- "POSTGRES_PORT": os.getenv("POSTGRES_PORT", "not set"),- "POSTGRES_DATABASE": os.getenv("POSTGRES_DATABASE", "not set"),- "POSTGRES_USER": os.getenv("POSTGRES_USER", "not set"),- "POSTGRES_PASSWORD": "***" if os.getenv("POSTGRES_PASSWORD") else "not set",- }-- context.log.info("PostgreSQL environment variables:")- for key, value in env_vars.items():- context.log.info(f" {key}: {value}")--- tags={"owner": JobOwners.TEAM_INGESTION.value},- executor_def=k8s_job_executor,-)-def persons_new_backfill_job():- """- Backfill posthog_persons data from source to destination Postgres database.- Divides the ID space into chunks and processes them in parallel.- """- id_range = get_id_range_for_pnb()- chunks = create_chunks_for_pnb(id_range)- chunks.map(copy_chunk)diff --git a/posthog/dags/persons_without_distinct_ids_cleanup.py b/posthog/dags/persons_without_distinct_ids_cleanup.pydeleted file mode 100644index a5f4dce52ece..000000000000--- a/posthog/dags/persons_without_distinct_ids_cleanup.py+++ /dev/null@@ -1,423 +0,0 @@-"""Dagster job for deleting posthog_persons rows that have no associated posthog_persondistinctid rows."""--import time-from typing import Any--import dagster-import psycopg2-import psycopg2.errors-from dagster_k8s import k8s_job_executor--from posthog.clickhouse.cluster import ClickhouseCluster-from posthog.clickhouse.custom_metrics import MetricsClient-from posthog.dags.common import JobOwners--MAX_RETRY_ATTEMPTS = 5-METRIC_PUBLISH_INTERVAL = 100---class PersonsNoDistinctIdsCleanupConfig(dagster.Config):- """Configuration for the persons without distinct ids cleanup job."""-- chunk_size: int = 1_000_000 # ID range per chunk- batch_size: int = 1000 # Records to scan for a parent person or delete in a single transaction- max_id: int | None = None # Optional override for max ID to resume from partial state- min_id: int | None = None # Optional override for min ID to resume from partial state- persons_table: str = "posthog_persons_new" # Override once the table name swap is complete!---def get_id_range_for_pwdc(- context: dagster.OpExecutionContext,- config: PersonsNoDistinctIdsCleanupConfig,- database: dagster.ResourceParam[psycopg2.extensions.connection],-) -> tuple[int, int]:- """- Query source database for MIN(id) and MAX(id) from posthog_person table.- If min_id or max_id is provided in config, uses that instead of querying.- Returns tuple (min_id, max_id).- """- with database.cursor() as cursor:- # Use config min_id if provided, otherwise query database- if config.min_id is not None:- min_id = config.min_id- context.log.info(f"Using configured min_id override: {config.min_id}")- else:- # Always query for min_id- min_query = f"SELECT MIN(id) as min_id FROM posthog_person"- context.log.info(f"Querying min ID: {min_query}")- cursor.execute(min_query)- min_result = cursor.fetchone()-- if min_result is None or min_result["min_id"] is None:- context.log.exception("Source table has no valid min ID")- # Note: No metrics client here as this is get_id_range_for_pwdc op, not copy_chunk- raise dagster.Failure("Source table has no valid min ID")-- min_id = int(min_result["min_id"])-- # Use config max_id if provided, otherwise query database- if config.max_id is not None:- max_id = config.max_id- context.log.info(f"Using configured max_id override: {max_id}")- else:- max_query = f"SELECT MAX(id) as max_id FROM posthog_person"- context.log.info(f"Querying max ID: {max_query}")- cursor.execute(max_query)- max_result = cursor.fetchone()-- if max_result is None or max_result["max_id"] is None:- context.log.exception("posthog_person table has no valid max ID")- # Note: No metrics client here as this is get_id_range_for_pwdc op, not copy_chunk- raise dagster.Failure("posthog_person table has no valid max ID")-- max_id = int(max_result["max_id"])-- # Validate that max_id >= min_id- if max_id < min_id:- error_msg = f"Invalid ID range: max_id ({max_id}) < min_id ({min_id})"- context.log.error(error_msg)- # Note: No metrics client here as this is get_id_range op, not copy_chunk- raise dagster.Failure(error_msg)-- context.log.info(f"ID range: min={min_id}, max={max_id}, total_ids={max_id - min_id + 1}")- context.add_output_metadata(- {- "min_id": dagster.MetadataValue.int(min_id),- "min_id_source": dagster.MetadataValue.text("config" if config.min_id is not None else "database"),- "max_id": dagster.MetadataValue.int(max_id),- "max_id_source": dagster.MetadataValue.text("config" if config.max_id is not None else "database"),- "total_ids": dagster.MetadataValue.int(max_id - min_id + 1),- }- )-- return (min_id, max_id)--[email protected](out=dagster.DynamicOut(tuple[int, int]))-def create_chunks_for_pwdc(- context: dagster.OpExecutionContext,- config: PersonsNoDistinctIdsCleanupConfig,- id_range: tuple[int, int],-):- """- Divide ID space into chunks of chunk_size.- Yields DynamicOutput for each chunk in reverse order (highest IDs first, lowest IDs last).- This ensures that if the job fails partway through, the final chunk to process will be- the one starting at the source table's min_id.- """- min_id, max_id = id_range- chunk_size = config.chunk_size-- # First, collect all chunks- chunks = []- chunk_min = min_id- chunk_num = 0-- while chunk_min <= max_id:- chunk_max = min(chunk_min + chunk_size - 1, max_id)- chunks.append((chunk_min, chunk_max, chunk_num))- chunk_min = chunk_max + 1- chunk_num += 1-- context.log.info(f"Created {chunk_num} chunks total")-- # Yield chunks in reverse order (highest IDs first)- for chunk_min, chunk_max, chunk_num in reversed(chunks):- chunk_key = f"chunk_{chunk_min}_{chunk_max}"- context.log.info(f"Yielding chunk {chunk_num}: {chunk_min} to {chunk_max}")- yield dagster.DynamicOutput(- value=(chunk_min, chunk_max),- mapping_key=chunk_key,- )---def scan_delete_chunk_for_pwdc(- context: dagster.OpExecutionContext,- config: PersonsNoDistinctIdsCleanupConfig,- chunk: tuple[int, int],- database: dagster.ResourceParam[psycopg2.extensions.connection],- cluster: dagster.ResourceParam[ClickhouseCluster],-) -> dict[str, Any]:- """- Scan posthog_person_new table for records that have no associated posthog_persondistinctid row,- and deletes the corresponding posthog_person_new row.- Processes in batches of batch_size records.- """- chunk_min, chunk_max = chunk- batch_size = config.batch_size- chunk_id = f"chunk_{chunk_min}_{chunk_max}"- job_name = context.run.job_name-- # Initialize metrics client- metrics_client = MetricsClient(cluster)-- context.log.info(f"Starting chunk scan and delete for ID range: {chunk_min} to {chunk_max}")-- total_records_deleted = 0- batch_start_id = chunk_min- failed_batch_start_id: int | None = None-- try:- with database.cursor() as cursor:- # Set session-level settings once for the entire chunk- cursor.execute("SET application_name = 'delete_persons_with_no_distinct_ids'")- cursor.execute("SET lock_timeout = '5s'")- cursor.execute("SET statement_timeout = '30min'")- cursor.execute("SET maintenance_work_mem = '12GB'")- cursor.execute("SET work_mem = '512MB'")- cursor.execute("SET temp_buffers = '512MB'")- cursor.execute("SET max_parallel_workers_per_gather = 2")- cursor.execute("SET max_parallel_maintenance_workers = 2")- cursor.execute("SET synchronous_commit = off")-- # Initialize accumulator variables for metrics- accumulated_records_attempted = 0- accumulated_records_deleted = 0- accumulated_batches_scanned = 0- batch_counter = 0-- retry_attempt = 0- while batch_start_id <= chunk_max:- try:- # Track batch start time for duration metric- batch_start_time = time.time()-- # Calculate batch end ID- batch_end_id = min(batch_start_id + batch_size, chunk_max)-- # Track records attempted - this is also our exit condition- records_scanned = batch_end_id - batch_start_id- if records_scanned <= 0:- break-- # Begin transaction (settings already applied at session level)- cursor.execute("BEGIN")-- # Execute DELETE FROM posthog_person_new with NOT EXISTS check on- # associated posthog_persondistinctid rows- scan_delete_query = f"""-DELETE FROM {config.persons_table} AS p-WHERE p.id >= %s AND p.id <= %s- AND NOT EXISTS (- SELECT 1- FROM posthog_persondistinctid AS pd- WHERE pd.person_id = p.id- AND pd.team_id = p.team_id- )-ORDER BY p.id DESC-"""- cursor.execute(scan_delete_query, (batch_start_id, batch_end_id))- records_deleted = cursor.rowcount-- # Commit the transaction- cursor.execute("COMMIT")-- # Accumulate metrics locally- accumulated_records_attempted += records_scanned + 1- accumulated_records_deleted += records_deleted- accumulated_batches_scanned += 1- batch_counter += 1- total_records_deleted += records_deleted-- # this metric is inaccurate if we don't emit every batch or average it etc.- batch_duration_seconds = time.time() - batch_start_time- try:- metrics_client.increment(- "persons_wo_distinct_ids_batch_duration_seconds_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(batch_duration_seconds),- ).result()- except Exception:- pass-- # Publish accumulated metrics every METRIC_PUBLISH_INTERVAL batches as totals- if batch_counter >= METRIC_PUBLISH_INTERVAL:- try:- metrics_client.increment(- "persons_wo_distinct_ids_records_attempted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_attempted),- ).result()- except Exception:- pass # Don't fail on metrics error- try:- metrics_client.increment(- "persons_wo_distinct_ids_batches_scanned_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_batches_scanned),- ).result()- except Exception:- pass- try:- metrics_client.increment(- "persons_wo_distinct_ids_records_deleted_total",- labels={"job_name": job_name, "chunk_id": chunk_id},- value=float(accumulated_records_deleted),- ).result()- except Exception:- pass- # Reset accumulators- accumulated_records_attempted = 0- accumulated_records_deleted = 0- accumulated_batches_scanned = 0- batch_counter = 0-- context.log.info(- f"Deleted batch: {records_deleted} records "- f"(chunk {chunk_min}-{chunk_max}, batch ID range {batch_start_id} to {batch_end_id})"- )-- # Update batch_start_id for next iteration- batch_start_id = batch_end_id + 1- retry_attempt = 0-- except Exception as batch_error:- # Rollback transaction on error- try:- cursor.execute("ROLLBACK")- except Exception as rollback_error:- context.log.exception(- f"Failed to rollback transaction for batch starting at ID {batch_start_id}"- f"in chunk {chunk_min}-{chunk_max}: {str(rollback_error)}"- )- pass # Ignore rollback errors-- # Check if error is a serialization failure, pause and retry if so- serialization_failure_class = getattr(psycopg2.errors, "SerializationFailure", None)- is_serialization_failure = (- serialization_failure_class is not None and isinstance(batch_error, serialization_failure_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40001")- if is_serialization_failure:- error_msg = (- f"Serialization failure detected for batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}. Error is: {batch_error}. "- "This is expected due to concurrent transactions. "- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Check if error is a deadlock, pause and retry if so- deadlock_detected_class = getattr(psycopg2.errors, "DeadlockDetected", None)- is_deadlock = (- deadlock_detected_class is not None and isinstance(batch_error, deadlock_detected_class)- ) or (isinstance(batch_error, psycopg2.Error) and getattr(batch_error, "pgcode", None) == "40P01")- if is_deadlock:- error_msg = (- f"Deadlock detected for batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}. Error is: {batch_error}. "- "This is expected due to concurrent transactions. "- )- context.log.warning(error_msg)- if retry_attempt < MAX_RETRY_ATTEMPTS:- retry_attempt += 1- context.log.warning(f"Retrying batch {retry_attempt} of {MAX_RETRY_ATTEMPTS}...")- time.sleep(1)- continue-- # Handle unexpected errors by bubbling up to dagster.Failure- failed_batch_start_id = batch_start_id- error_msg = (- f"Failed to scan and delete rows in batch starting at ID {batch_start_id} "- f"in chunk {chunk_min}-{chunk_max}: {str(batch_error)}"- )- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "persons_wo_distinct_ids_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "batch_scan_delete_failed"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.text("N/A"),- "error_message": dagster.MetadataValue.text(str(batch_error)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from batch_error-- except dagster.Failure:- # Re-raise Dagster failures as-is (they already have metadata and metrics)- raise-- except Exception as e:- # Catch any other unexpected errors- error_msg = f"Unexpected error scanning and deleting from chunk {chunk_min}-{chunk_max}: {str(e)}"- context.log.exception(error_msg)- # Report fatal error metric before raising- try:- metrics_client.increment(- "persons_wo_distinct_ids_error",- labels={"job_name": job_name, "chunk_id": chunk_id, "reason": "unexpected_scan_delete_error"},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error- raise dagster.Failure(- description=error_msg,- metadata={- "chunk_min_id": dagster.MetadataValue.int(chunk_min),- "chunk_max_id": dagster.MetadataValue.int(chunk_max),- "failed_batch_start_id": dagster.MetadataValue.int(failed_batch_start_id)- if failed_batch_start_id- else dagster.MetadataValue.int(batch_start_id),- "error_message": dagster.MetadataValue.text(str(e)),- "records_deleted_before_failure": dagster.MetadataValue.int(total_records_deleted),- },- ) from e-- context.log.info(f"Completed chunk {chunk_min}-{chunk_max}: deleted {total_records_deleted} records")-- # Emit metric for chunk completion- run_id = context.run.run_id- try:- metrics_client.increment(- "persons_wo_distinct_ids_chunks_completed_total",- labels={"job_name": job_name, "run_id": run_id, "chunk_id": chunk_id},- value=1.0,- ).result()- except Exception:- pass # Don't fail on metrics error-- context.add_output_metadata(- {- "chunk_min": dagster.MetadataValue.int(chunk_min),- "chunk_max": dagster.MetadataValue.int(chunk_max),- "records_deleted": dagster.MetadataValue.int(total_records_deleted),- }- )-- return {- "chunk_min": chunk_min,- "chunk_max": chunk_max,- "records_deleted": total_records_deleted,- }--- tags={"owner": JobOwners.TEAM_INGESTION.value},- executor_def=k8s_job_executor,-)-def persons_without_distinct_ids_cleanup_job():- """- Scan posthog_person table for records that have no associated posthog_persondistinctid- rows, deleting the corresponding posthog_person rows.- Divides the ID space into chunks and processes them in parallel.- """- id_range = get_id_range_for_pwdc()- chunks = create_chunks_for_pwdc(id_range)- chunks.map(scan_delete_chunk_for_pwdc)diff --git a/posthog/dags/tests/test_delete_persons_from_trigger_log.py b/posthog/dags/tests/test_delete_persons_from_trigger_log.pydeleted file mode 100644index 8db3cd4d5111..000000000000--- a/posthog/dags/tests/test_delete_persons_from_trigger_log.py+++ /dev/null@@ -1,461 +0,0 @@-"""Tests for the delete persons from trigger log job."""--from unittest.mock import MagicMock, patch--import psycopg2-from dagster import build_op_context--from posthog.dags.delete_persons_from_trigger_log import (- DeletePersonsFromTriggerLogConfig,- create_team_chunks_for_dpft,- get_team_ids_for_dpft,- scan_delete_chunk_for_dpft,-)---class MockPsycopg2Error(psycopg2.Error):- """Mock psycopg2.Error that allows setting pgcode."""-- def __init__(self, message: str, pgcode: str):- super().__init__(message)- # Store pgcode in a private attribute- self._pgcode = pgcode-- @property- def pgcode(self) -> str:- """Override pgcode property to return our custom value."""- return self._pgcode---def create_mock_psycopg2_error(message: str, pgcode: str) -> Exception:- """Create a mock psycopg2.Error with a specific pgcode."""- return MockPsycopg2Error(message, pgcode)---class TestGetTeamIdsForDpft:- """Test the get_team_ids_for_dpft function."""-- def test_get_team_ids_returns_distinct_teams(self):- """Test that database is queried for distinct team_ids with persons to delete."""- mock_db = MagicMock()- cursor = MagicMock()- cursor.fetchall.return_value = [{"team_id": 1}, {"team_id": 2}, {"team_id": 5}]- mock_db.cursor.return_value.__enter__ = MagicMock(return_value=cursor)- mock_db.cursor.return_value.__exit__ = MagicMock(return_value=False)-- context = build_op_context(resources={"database": mock_db})-- result = get_team_ids_for_dpft(context)-- assert result == [1, 2, 5]-- # Verify query was executed- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert any("SELECT DISTINCT pdl.team_id" in call for call in execute_calls)- assert any("FROM posthog_person_deletes_log" in call for call in execute_calls)- assert any("EXISTS" in call for call in execute_calls)-- def test_get_team_ids_returns_empty_list_when_no_teams(self):- """Test that empty list is returned when no teams have persons to delete."""- mock_db = MagicMock()- cursor = MagicMock()- cursor.fetchall.return_value = []- mock_db.cursor.return_value.__enter__ = MagicMock(return_value=cursor)- mock_db.cursor.return_value.__exit__ = MagicMock(return_value=False)-- context = build_op_context(resources={"database": mock_db})-- result = get_team_ids_for_dpft(context)-- assert result == []---class TestCreateTeamChunksForDpft:- """Test the create_team_chunks_for_dpft function."""-- def test_create_chunks_for_each_team(self):- """Test that chunks are created for each team_id."""- team_ids = [1, 2, 5, 10]-- context = build_op_context()- chunks = list(create_team_chunks_for_dpft(context, team_ids))-- assert len(chunks) == 4- assert [chunk.value for chunk in chunks] == [1, 2, 5, 10]- assert [chunk.mapping_key for chunk in chunks] == ["team_1", "team_2", "team_5", "team_10"]-- def test_create_chunks_handles_empty_team_list(self):- """Test that no chunks are created for empty team list."""- team_ids: list[int] = []-- context = build_op_context()- chunks = list(create_team_chunks_for_dpft(context, team_ids))-- assert len(chunks) == 0---def create_mock_database_resource(rowcount_values=None, fetchall_results=None):- """- Create a mock database resource that mimics psycopg2.extensions.connection.-- Args:- rowcount_values: List of rowcount values to return per DELETE call.- If None, defaults to 0. If a single int, uses that for all calls.- fetchall_results: List of results to return from fetchall() calls (for SELECT queries).- Each result should be a list of dict-like objects with "id" and "team_id" keys.- If None, defaults to empty list.- """- mock_cursor = MagicMock()- if rowcount_values is None:- mock_cursor.rowcount = 0- elif isinstance(rowcount_values, int):- mock_cursor.rowcount = rowcount_values- else:- # Use side_effect to return different rowcounts per call- call_count = [0]-- def get_rowcount():- if call_count[0] < len(rowcount_values):- result = rowcount_values[call_count[0]]- call_count[0] += 1- return result- return rowcount_values[-1] if rowcount_values else 0-- mock_cursor.rowcount = property(lambda self: get_rowcount())-- mock_cursor.execute = MagicMock()- mock_cursor.fetchone = MagicMock()-- # Setup fetchall to return scan results- if fetchall_results is None:- mock_cursor.fetchall = MagicMock(return_value=[])- elif isinstance(fetchall_results, list):- fetchall_call_count = [0]-- def get_fetchall_result():- if fetchall_call_count[0] < len(fetchall_results):- result = fetchall_results[fetchall_call_count[0]]- fetchall_call_count[0] += 1- return result- return []-- mock_cursor.fetchall = MagicMock(side_effect=get_fetchall_result)- else:- mock_cursor.fetchall = MagicMock(return_value=fetchall_results)-- # Make cursor() return a context manager- mock_conn = MagicMock()- mock_conn.cursor.return_value.__enter__ = MagicMock(return_value=mock_cursor)- mock_conn.cursor.return_value.__exit__ = MagicMock(return_value=False)-- return mock_conn---def create_mock_cluster_resource():- """Create a mock ClickhouseCluster resource."""- return MagicMock()---class TestScanDeleteChunkForDpft:- """Test the scan_delete_chunk_for_dpft function."""-- def test_scan_delete_chunk_single_batch_success(self):- """Test successful scan and delete of a single batch for a team."""- config = DeletePersonsFromTriggerLogConfig(batch_size=100)- team_id = 1-- # Create 50 person records to delete for this team- ids_to_delete = [{"id": i, "team_id": 1} for i in range(1, 51)]-- mock_db = create_mock_database_resource(- rowcount_values=1, # Each DELETE deletes 1 person- fetchall_results=[ids_to_delete, []], # First batch returns IDs, second returns empty (done)- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_dpft(context, config, team_id)-- # Verify result- assert result["team_id"] == 1- assert result["records_deleted"] == 50-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify SELECT scan query format (keyset pagination, no OFFSET)- scan_calls = [call for call in execute_calls if "FROM posthog_person_deletes_log" in call]- assert len(scan_calls) >= 1- scan_query = scan_calls[0]- assert "WHERE pdl.team_id = %s" in scan_query- assert "ORDER BY pdl.id" in scan_query- assert "LIMIT" in scan_query- assert "OFFSET" not in scan_query # Keyset pagination doesn't use OFFSET- assert "EXISTS" in scan_query-- # Verify DELETE queries were called (one per person)- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_person_new" in call]- assert len(delete_calls) == 50-- def test_scan_delete_chunk_multiple_batches_with_keyset_pagination(self):- """Test scan and delete with multiple batches using keyset pagination."""- config = DeletePersonsFromTriggerLogConfig(batch_size=50)- team_id = 1-- # Create IDs to delete for each batch (simulate keyset pagination)- # Batch 1: IDs 1-50, Batch 2: IDs 51-100, Batch 3: empty (done)- fetchall_results = [- [{"id": i, "team_id": 1} for i in range(1, 51)],- [{"id": i, "team_id": 1} for i in range(51, 101)],- [], # Empty result to signal completion- ]-- mock_db = create_mock_database_resource(- rowcount_values=1,- fetchall_results=fetchall_results,- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_dpft(context, config, team_id)-- assert result["team_id"] == 1- assert result["records_deleted"] == 100-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify SELECT scan called multiple times (keyset pagination)- scan_calls = [call for call in execute_calls if "FROM posthog_person_deletes_log" in call]- assert len(scan_calls) >= 2-- # Second scan should include "WHERE pdl.id > %s" for keyset pagination- if len(scan_calls) > 1:- second_scan = scan_calls[1]- assert "WHERE pdl.team_id = %s" in second_scan- assert "AND pdl.id > %s" in second_scan-- # Verify DELETE called 100 times- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_person_new" in call]- assert len(delete_calls) == 100-- def test_scan_delete_chunk_serialization_failure_retry(self):- """Test that serialization failure triggers retry."""- config = DeletePersonsFromTriggerLogConfig(batch_size=100)- team_id = 1-- ids_to_delete = [{"id": i, "team_id": 1} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_to_delete, []])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- scan_attempts = [0]-- def execute_side_effect(query, *args):- if "FROM posthog_person_deletes_log" in query:- scan_attempts[0] += 1- if scan_attempts[0] == 1:- error = create_mock_psycopg2_error("could not serialize access", "40001")- raise error- elif "DELETE FROM posthog_person_new" in query:- cursor.rowcount = 1-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.delete_persons_from_trigger_log.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_dpft(context, config, team_id)-- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- scan_calls = [call for call in execute_calls if "FROM posthog_person_deletes_log" in call]- assert len(scan_calls) >= 2-- def test_scan_delete_chunk_deadlock_retry(self):- """Test that deadlock triggers retry."""- config = DeletePersonsFromTriggerLogConfig(batch_size=100)- team_id = 1-- ids_to_delete = [{"id": i, "team_id": 1} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_to_delete, []])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- scan_attempts = [0]-- def execute_side_effect(query, *args):- if "FROM posthog_person_deletes_log" in query:- scan_attempts[0] += 1- if scan_attempts[0] == 1:- error = create_mock_psycopg2_error("deadlock detected", "40P01")- raise error- elif "DELETE FROM posthog_person_new" in query:- cursor.rowcount = 1-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.delete_persons_from_trigger_log.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_dpft(context, config, team_id)-- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- scan_calls = [call for call in execute_calls if "FROM posthog_person_deletes_log" in call]- assert len(scan_calls) >= 2-- def test_scan_delete_chunk_error_handling(self):- """Test error handling on non-retryable errors."""- config = DeletePersonsFromTriggerLogConfig(batch_size=100)- team_id = 1-- ids_to_delete = [{"id": i, "team_id": 1} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_to_delete])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- def execute_side_effect(query, *args):- if "FROM posthog_person_deletes_log" in query:- raise Exception("Connection lost")-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- from dagster import Failure-- try:- scan_delete_chunk_for_dpft(context, config, team_id)- raise AssertionError("Expected Failure to be raised")- except Failure as e:- assert e.description is not None- assert "team_id" in e.description-- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- def test_scan_delete_chunk_query_format(self):- """Test that queries have correct format for team-based processing."""- config = DeletePersonsFromTriggerLogConfig(batch_size=100)- team_id = 1-- ids_to_delete = [{"id": i, "team_id": 1} for i in range(1, 11)]- mock_db = create_mock_database_resource(- rowcount_values=1,- fetchall_results=[ids_to_delete, []],- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_dpft(context, config, team_id)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify DELETE queries- delete_queries = [call for call in execute_calls if "DELETE FROM posthog_person_new" in call]- assert len(delete_queries) == 10-- delete_query = delete_queries[0]- assert "DELETE FROM posthog_person_new" in delete_query- assert "WHERE team_id = %s AND id = %s" in delete_query-- # Verify SELECT query for team-based filtering- scan_query = next((call for call in execute_calls if "FROM posthog_person_deletes_log" in call), None)- assert scan_query is not None- assert "WHERE pdl.team_id = %s" in scan_query- assert "FROM posthog_person_deletes_log" in scan_query- assert "ORDER BY pdl.id" in scan_query- assert "LIMIT" in scan_query- assert "EXISTS" in scan_query- assert "OFFSET" not in scan_query # Keyset pagination-- def test_scan_delete_chunk_session_settings_applied_once(self):- """Test that SET statements are applied once at session level."""- config = DeletePersonsFromTriggerLogConfig(batch_size=50)- team_id = 1-- fetchall_results = [- [{"id": i, "team_id": 1} for i in range(1, 26)],- [{"id": i, "team_id": 1} for i in range(51, 76)],- [],- ]- mock_db = create_mock_database_resource(- rowcount_values=1,- fetchall_results=fetchall_results,- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_dpft(context, config, team_id)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- set_statements = [- "SET application_name",- "SET lock_timeout",- "SET statement_timeout",- "SET maintenance_work_mem",- "SET work_mem",- "SET temp_buffers",- "SET max_parallel_workers_per_gather",- "SET max_parallel_maintenance_workers",- "SET synchronous_commit",- ]-- for stmt in set_statements:- count = sum(1 for call in execute_calls if stmt in call)- assert count == 1, f"Expected {stmt} to be called once, but it was called {count} times"-- # Verify SET statements come before BEGIN statements- set_indices = [i for i, call in enumerate(execute_calls) if any(stmt in call for stmt in set_statements)]- begin_indices = [i for i, call in enumerate(execute_calls) if call == "BEGIN"]-- if set_indices and begin_indices:- assert max(set_indices) < min(begin_indices)diff --git a/posthog/dags/tests/test_fix_missing_person_overrides.py b/posthog/dags/tests/test_fix_missing_person_overrides.pydeleted file mode 100644index 5ea140e03101..000000000000--- a/posthog/dags/tests/test_fix_missing_person_overrides.py+++ /dev/null@@ -1,424 +0,0 @@-from datetime import datetime-from uuid import UUID, uuid4--from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events--from posthog.clickhouse.client import sync_execute-from posthog.dags.fix_missing_person_overrides import (- fix_missing_person_overrides_job,- get_existing_override,- get_mismatched_distinct_ids,- get_missing_overrides_for_distinct_ids,- insert_override_batch,-)---def insert_pdi2_records(records: list[tuple[int, str, UUID, int, int]]) -> None:- """Insert records into person_distinct_id2: (team_id, distinct_id, person_id, version, is_deleted)"""- sync_execute(- "INSERT INTO person_distinct_id2 (team_id, distinct_id, person_id, version, is_deleted) VALUES",- records,- )---def insert_override_records(records: list[tuple[int, str, UUID, int, int]]) -> None:- """Insert records into person_distinct_id_overrides: (team_id, distinct_id, person_id, version, is_deleted)"""- sync_execute(- "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted, _timestamp, _offset, _partition) VALUES",- [(r[0], r[1], r[2], r[3], r[4], datetime(2025, 1, 1), 0, 0) for r in records],- )---def get_all_overrides(team_id: int) -> list[tuple[str, str]]:- """Get all overrides for a team: (distinct_id, person_id)"""- result = sync_execute(- """- SELECT distinct_id, argMax(person_id, version) as person_id- FROM person_distinct_id_overrides- WHERE team_id = %(team_id)s- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0- """,- {"team_id": team_id},- )- return [(row[0], str(row[1])) for row in result]---class TestGetMismatchedDistinctIds(ClickhouseTestMixin, BaseTest):- def test_finds_distinct_ids_where_override_differs_from_pdi2(self):- """When an override exists, person_id on events differs from pdi.person_id."""- old_person_id = uuid4()- new_person_id = uuid4()-- # pdi2 says distinct_id "user_a" -> old_person_id- insert_pdi2_records([(self.team.id, "user_a", old_person_id, 1, 0)])-- # Override says distinct_id "user_a" -> new_person_id- insert_override_records([(self.team.id, "user_a", new_person_id, 1, 0)])-- # Create an event with this distinct_id- _create_event(- event="test_event",- distinct_id="user_a",- team=self.team,- )- flush_persons_and_events()-- # The HogQL query should find the distinct_id with a mismatch- result = get_mismatched_distinct_ids(self.team)-- assert len(result) == 1- assert result[0] == "user_a"-- def test_returns_empty_when_no_mismatches(self):- """When override matches pdi2, no mismatch is detected."""- person_id = uuid4()-- # pdi2 says distinct_id "user_b" -> person_id- insert_pdi2_records([(self.team.id, "user_b", person_id, 1, 0)])-- # Override also says distinct_id "user_b" -> same person_id- insert_override_records([(self.team.id, "user_b", person_id, 1, 0)])-- # Create an event- _create_event(- event="test_event",- distinct_id="user_b",- team=self.team,- )- flush_persons_and_events()-- result = get_mismatched_distinct_ids(self.team)-- assert len(result) == 0-- def test_returns_empty_when_no_events_exist(self):- """When no events exist, no mismatches are found."""- result = get_mismatched_distinct_ids(self.team)- assert len(result) == 0-- def test_min_date_filters_events(self):- """Events before min_date are excluded."""- old_person_id = uuid4()- new_person_id = uuid4()-- insert_pdi2_records([(self.team.id, "user_date", old_person_id, 1, 0)])- insert_override_records([(self.team.id, "user_date", new_person_id, 1, 0)])-- # Create event in January 2024- _create_event(- event="old_event",- distinct_id="user_date",- team=self.team,- timestamp=datetime(2024, 1, 15),- )- flush_persons_and_events()-- # Query with min_date in February - should find nothing- result = get_mismatched_distinct_ids(self.team, min_date="2024-02-01")- assert len(result) == 0-- # Query with min_date in January - should find the mismatch- result = get_mismatched_distinct_ids(self.team, min_date="2024-01-01")- assert len(result) == 1-- def test_max_date_filters_events(self):- """Events on or after max_date are excluded."""- old_person_id = uuid4()- new_person_id = uuid4()-- insert_pdi2_records([(self.team.id, "user_max", old_person_id, 1, 0)])- insert_override_records([(self.team.id, "user_max", new_person_id, 1, 0)])-- # Create event in March 2024- _create_event(- event="march_event",- distinct_id="user_max",- team=self.team,- timestamp=datetime(2024, 3, 15),- )- flush_persons_and_events()-- # Query with max_date in March - should find nothing (exclusive)- result = get_mismatched_distinct_ids(self.team, max_date="2024-03-01")- assert len(result) == 0-- # Query with max_date in April - should find the mismatch- result = get_mismatched_distinct_ids(self.team, max_date="2024-04-01")- assert len(result) == 1-- def test_date_range_filters_events(self):- """Only events within the date range are included."""- old_person_id = uuid4()- new_person_id = uuid4()-- insert_pdi2_records([(self.team.id, "user_range", old_person_id, 1, 0)])- insert_override_records([(self.team.id, "user_range", new_person_id, 1, 0)])-- # Create event in February 2024- _create_event(- event="feb_event",- distinct_id="user_range",- team=self.team,- timestamp=datetime(2024, 2, 15),- )- flush_persons_and_events()-- # Query with range that excludes the event- result = get_mismatched_distinct_ids(self.team, min_date="2024-03-01", max_date="2024-04-01")- assert len(result) == 0-- # Query with range that includes the event- result = get_mismatched_distinct_ids(self.team, min_date="2024-02-01", max_date="2024-03-01")- assert len(result) == 1---class TestInsertOverrideBatch(ClickhouseTestMixin, BaseTest):- def test_inserts_batch_of_overrides(self):- person_id_1 = uuid4()- person_id_2 = uuid4()-- insert_override_batch(- [- (self.team.id, "batch_user_1", str(person_id_1), 1),- (self.team.id, "batch_user_2", str(person_id_1), 1),- (self.team.id, "batch_user_3", str(person_id_2), 2),- ]- )-- result = get_existing_override(self.team.id, "batch_user_1")- assert result is not None- assert result[0] == str(person_id_1)-- result = get_existing_override(self.team.id, "batch_user_2")- assert result is not None- assert result[0] == str(person_id_1)-- result = get_existing_override(self.team.id, "batch_user_3")- assert result is not None- assert result[0] == str(person_id_2)-- def test_handles_empty_batch(self):- insert_override_batch([])---class TestGetMissingOverridesForDistinctIds(ClickhouseTestMixin, BaseTest):- def test_returns_empty_for_empty_distinct_ids(self):- result = get_missing_overrides_for_distinct_ids(self.team.id, [])- assert len(result) == 0-- def test_returns_empty_for_nonexistent_distinct_id(self):- result = get_missing_overrides_for_distinct_ids(self.team.id, ["nonexistent_user"])- assert len(result) == 0-- def test_returns_missing_overrides(self):- person_id = uuid4()-- # Insert test data - two distinct_ids mapping to the same person- insert_pdi2_records(- [- (self.team.id, "has_override", person_id, 1, 0),- (self.team.id, "no_override", person_id, 1, 0),- ]- )- # Only one has an override- insert_override_records([(self.team.id, "has_override", person_id, 1, 0)])-- # Query for missing overrides by distinct_id- result = get_missing_overrides_for_distinct_ids(self.team.id, ["has_override", "no_override"])-- # Should return only the one without an override- assert len(result) == 1- assert result[0][0] == "no_override"- assert result[0][1] == str(person_id)-- def test_returns_correct_person_id_from_pdi2(self):- """Verify we get the person_id from pdi2, not from some other source."""- pdi2_person_id = uuid4()-- # pdi2 says distinct_id maps to pdi2_person_id- insert_pdi2_records([(self.team.id, "test_user", pdi2_person_id, 1, 0)])-- result = get_missing_overrides_for_distinct_ids(self.team.id, ["test_user"])-- assert len(result) == 1- assert result[0][0] == "test_user"- assert result[0][1] == str(pdi2_person_id)---class TestIntegration(ClickhouseTestMixin, BaseTest):- def test_full_flow_creates_correct_override(self):- """- Integration test: verify that chaining get_mismatched_distinct_ids and- get_missing_overrides_for_distinct_ids produces the correct override.-- Scenario: Event was written with OLD person_id, then pdi2 was updated to NEW person_id,- but no override was created. The job should create an override pointing to NEW.- """- old_person_id = uuid4()- new_person_id = uuid4()-- # pdi2 says distinct_id -> NEW person_id (this is the source of truth after merge)- insert_pdi2_records([(self.team.id, "merged_user", new_person_id, 2, 0)])-- # Event was written with OLD person_id (before the merge)- # No override exists, so person_id on event stays as OLD- _create_event(- event="old_event",- distinct_id="merged_user",- person_id=str(old_person_id),- team=self.team,- )- flush_persons_and_events()-- # Step 1: Find mismatched distinct_ids- # person_id (OLD, from event) != pdi.person_id (NEW, from pdi2)- mismatched = get_mismatched_distinct_ids(self.team)- assert len(mismatched) == 1- assert mismatched[0] == "merged_user"-- # Step 2: Get missing overrides for those distinct_ids- missing = get_missing_overrides_for_distinct_ids(self.team.id, mismatched)- assert len(missing) == 1- distinct_id, person_id, version = missing[0]-- # The override should point to NEW person_id (from pdi2), not OLD- assert distinct_id == "merged_user"- assert person_id == str(new_person_id)-- # Step 3: Insert the override- insert_override_batch([(self.team.id, distinct_id, person_id, max(version, 1))])-- # Verify the override was created correctly- override = get_existing_override(self.team.id, "merged_user")- assert override is not None- assert override[0] == str(new_person_id)---class TestFixMissingPersonOverridesJob(ClickhouseTestMixin, BaseTest):- def test_inserts_overrides_for_mismatched_distinct_ids(self):- """Job inserts overrides for distinct_ids where event person_id != pdi2 person_id."""- old_person_id = uuid4()- new_person_id = uuid4()-- # pdi2 says distinct_id -> NEW person_id (source of truth after merge)- insert_pdi2_records([(self.team.id, "job_test_user", new_person_id, 2, 0)])-- # Event was written with OLD person_id (before the merge)- _create_event(- event="test_event",- distinct_id="job_test_user",- person_id=str(old_person_id),- team=self.team,- )- flush_persons_and_events()-- # Run the job with dry_run=False- fix_missing_person_overrides_job.execute_in_process(- run_config={- "ops": {- "fix_missing_person_overrides_op": {- "config": {- "team_id": self.team.id,- "dry_run": False,- }- }- }- }- )-- # Verify override was created pointing to NEW person_id (from pdi2)- overrides = get_all_overrides(self.team.id)- override_dict = dict(overrides)-- assert "job_test_user" in override_dict- assert override_dict["job_test_user"] == str(new_person_id)-- def test_dry_run_does_not_insert(self):- """Job does not insert overrides when dry_run=True."""- old_person_id = uuid4()- new_person_id = uuid4()-- # pdi2 says distinct_id -> NEW person_id- insert_pdi2_records([(self.team.id, "dry_run_user", new_person_id, 2, 0)])-- # Event was written with OLD person_id- _create_event(- event="test_event",- distinct_id="dry_run_user",- person_id=str(old_person_id),- team=self.team,- )- flush_persons_and_events()-- # Run the job with dry_run=True- fix_missing_person_overrides_job.execute_in_process(- run_config={- "ops": {- "fix_missing_person_overrides_op": {- "config": {- "team_id": self.team.id,- "dry_run": True,- }- }- }- }- )-- # Verify no override was created- overrides = get_all_overrides(self.team.id)- assert len(overrides) == 0-- def test_skips_distinct_ids_with_existing_overrides(self):- """Job does not insert overrides for distinct_ids that already have one."""- old_person_id = uuid4()- new_person_id = uuid4()-- # pdi2 says both distinct_ids -> NEW person_id- insert_pdi2_records(- [- (self.team.id, "has_override", new_person_id, 2, 0),- (self.team.id, "no_override", new_person_id, 2, 0),- ]- )-- # One already has an override- insert_override_records([(self.team.id, "has_override", new_person_id, 2, 0)])-- # Events for both were written with OLD person_id- _create_event(- event="test_event",- distinct_id="has_override",- person_id=str(old_person_id),- team=self.team,- )- _create_event(- event="test_event",- distinct_id="no_override",- person_id=str(old_person_id),- team=self.team,- )- flush_persons_and_events()-- # Run the job- fix_missing_person_overrides_job.execute_in_process(- run_config={- "ops": {- "fix_missing_person_overrides_op": {- "config": {- "team_id": self.team.id,- "dry_run": False,- }- }- }- }- )-- # Verify only the missing override was created- overrides = get_all_overrides(self.team.id)- override_dict = dict(overrides)-- assert len(overrides) == 2- assert "has_override" in override_dict- assert "no_override" in override_dict- assert override_dict["no_override"] == str(new_person_id)diff --git a/posthog/dags/tests/test_person_property_reconciliation_restore.py b/posthog/dags/tests/test_person_property_reconciliation_restore.pydeleted file mode 100644index 8a2b2ba8cee5..000000000000--- a/posthog/dags/tests/test_person_property_reconciliation_restore.py+++ /dev/null@@ -1,1926 +0,0 @@-"""Integration tests for the person property restore job.--These tests use real database connections, not mocks.-"""--import json-import uuid as uuid_module-from datetime import UTC, datetime--import pytest--from posthog.dags.person_property_reconciliation_restore import (- compute_restore_diff,- fetch_backup_entries,- fetch_backup_entries_paginated,- fetch_person_by_id,- fetch_persons_by_ids,- restore_person_with_version_check,-)-from posthog.dags.tests.conftest import refresh_person_from_persons_db, save_person_to_persons_db-from posthog.models import Organization, Person, Team-from posthog.persons_db import persons_db_connection-from posthog.test.persons import create_person--# Exercises the persons DB directly (raw reads against the persons writer), so it must run against-# the real persons DB rather than the personhog fake.-pytestmark = pytest.mark.persons_db_direct---def create_backup_entry(- cursor,- job_id: str,- team_id: int,- person_id: int,- person_uuid: str,- properties_before: dict,- properties_after: dict,- version_before: int = 1,- version_after: int = 2,- properties_last_updated_at_before: dict | None = None,- properties_last_operation_before: dict | None = None,- properties_last_updated_at_after: dict | None = None,- properties_last_operation_after: dict | None = None,-) -> None:- """Helper to insert a backup entry directly into the backup table."""- cursor.execute(- """- INSERT INTO posthog_person_reconciliation_backup (- job_id, team_id, person_id, uuid,- properties, properties_last_updated_at, properties_last_operation,- version, is_identified, created_at, is_user_id,- pending_operations,- properties_after, properties_last_updated_at_after,- properties_last_operation_after, version_after- ) VALUES (- %s, %s, %s, %s::uuid,- %s, %s, %s,- %s, %s, %s, %s,- %s,- %s, %s, %s, %s- )- """,- (- job_id,- team_id,- person_id,- person_uuid,- json.dumps(properties_before),- json.dumps(properties_last_updated_at_before or {}),- json.dumps(properties_last_operation_before or {}),- version_before,- False,- datetime.now(UTC),- None,- json.dumps([]), # pending_operations- json.dumps(properties_after),- json.dumps(properties_last_updated_at_after or {}),- json.dumps(properties_last_operation_after or {}),- version_after,- ),- )---class TestComputeRestoreDiff:- """Unit tests for compute_restore_diff function."""-- def test_full_overwrite_returns_backup_state(self):- """Test that full_overwrite completely replaces current with backup."""- current_person = {- "properties": {"email": "[email protected]", "new_prop": "added_after"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="full_overwrite")-- assert result == {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }-- def test_full_overwrite_returns_none_when_already_matches(self):- """Test that full_overwrite returns None when current already matches backup."""- current_person = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="full_overwrite")-- assert result is None-- def test_restore_wins_restores_backed_up_and_preserves_new(self):- """Test that restore_wins restores backed-up properties and preserves new ones."""- current_person = {- "properties": {"email": "[email protected]", "new_prop": "added_after"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="restore_wins")-- assert result == {- "properties": {"email": "[email protected]", "new_prop": "added_after"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }-- def test_keep_newer_only_restores_unchanged_properties(self):- """Test that keep_newer only restores properties that haven't changed since backup."""- current_person = {- "properties": {- "email": "[email protected]", # unchanged since backup- "name": "Updated Name", # changed after backup- },- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_before = {- "properties": {"email": "[email protected]", "name": "Original Name"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_after = {- "properties": {"email": "[email protected]", "name": "Reconciled Name"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="keep_newer")-- # email unchanged since backup (current == after), so restore to before- # name was changed after backup (current != after), so keep current- assert result == {- "properties": {"email": "[email protected]", "name": "Updated Name"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- def test_keep_newer_returns_none_when_all_changed(self):- """Test keep_newer returns None when all properties changed after backup."""- current_person = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="keep_newer")-- # current != after, so property was changed after backup, keep it- assert result is None-- def test_restore_wins_restores_metadata_when_present_in_backup(self):- """Test that metadata is restored when it exists in the backup."""- current_person = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-06-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set_once"},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="restore_wins")-- assert result == {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set_once"},- }-- def test_restore_wins_removes_metadata_when_absent_from_backup(self):- """Test that metadata is removed when it doesn't exist in the backup."""- current_person = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-06-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }- backup_before = {- "properties": {"email": "[email protected]"},- # No metadata for email in backup- "properties_last_updated_at": {},- "properties_last_operation": {},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="restore_wins")-- assert result == {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- def test_keep_newer_restores_metadata_correctly(self):- """Test that keep_newer also restores metadata correctly."""- current_person = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-06-01T00:00:00"},- "properties_last_operation": {"email": "set"},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set_once"},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="keep_newer")-- # Property restored since current == after, metadata also restored- assert result == {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set_once"},- }-- def test_metadata_preserved_for_unchanged_properties(self):- """Test that metadata for properties not being restored stays unchanged."""- current_person = {- "properties": {"email": "[email protected]", "name": "Current Name"},- "properties_last_updated_at": {"email": "2024-06-01T00:00:00", "name": "2024-06-01T00:00:00"},- "properties_last_operation": {"email": "set", "name": "set"},- }- backup_before = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00"},- "properties_last_operation": {"email": "set_once"},- }- backup_after = {- "properties": {"email": "[email protected]"},- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="restore_wins")-- # Email restored with metadata, name preserved as-is (not in backup)- assert result == {- "properties": {"email": "[email protected]", "name": "Current Name"},- "properties_last_updated_at": {"email": "2024-01-01T00:00:00", "name": "2024-06-01T00:00:00"},- "properties_last_operation": {"email": "set_once", "name": "set"},- }-- def test_full_overwrite_many_properties(self):- """Test full_overwrite with many properties - complete replacement."""- current_person = {- "properties": {- "email": "[email protected]",- "name": "Current Name",- "phone": "+1234567890",- "new_prop_1": "added_after_backup",- "new_prop_2": "also_added_after",- "new_prop_3": "third_new_one",- },- "properties_last_updated_at": {- "email": "2024-06-01T00:00:00",- "name": "2024-06-01T00:00:00",- "phone": "2024-06-01T00:00:00",- },- "properties_last_operation": {- "email": "set",- "name": "set",- "phone": "set",- },- }- backup_before = {- "properties": {- "email": "[email protected]",- "name": "Original Name",- "phone": "+0987654321",- },- "properties_last_updated_at": {- "email": "2024-01-01T00:00:00",- "name": "2024-01-01T00:00:00",- },- "properties_last_operation": {- "email": "set_once",- "name": "set",- },- }- backup_after = {- "properties": {- "email": "[email protected]",- "name": "Reconciled Name",- "phone": "+1111111111",- },- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="full_overwrite")-- # Complete replacement - all current properties replaced with backup_before- assert result == {- "properties": {- "email": "[email protected]",- "name": "Original Name",- "phone": "+0987654321",- },- "properties_last_updated_at": {- "email": "2024-01-01T00:00:00",- "name": "2024-01-01T00:00:00",- },- "properties_last_operation": {- "email": "set_once",- "name": "set",- },- }-- def test_restore_wins_many_properties(self):- """Test restore_wins with many properties - restore backed-up, preserve new."""- current_person = {- "properties": {- "email": "[email protected]",- "name": "Current Name",- "phone": "+1234567890",- "new_prop_1": "added_after_backup",- "new_prop_2": "also_added_after",- "new_prop_3": "third_new_one",- },- "properties_last_updated_at": {- "email": "2024-06-01T00:00:00",- "name": "2024-06-01T00:00:00",- "new_prop_1": "2024-06-01T00:00:00",- },- "properties_last_operation": {- "email": "set",- "name": "set",- "new_prop_1": "set",- },- }- backup_before = {- "properties": {- "email": "[email protected]",- "name": "Original Name",- "phone": "+0987654321",- },- "properties_last_updated_at": {- "email": "2024-01-01T00:00:00",- "name": "2024-01-01T00:00:00",- },- "properties_last_operation": {- "email": "set_once",- "name": "set",- },- }- backup_after = {- "properties": {- "email": "[email protected]",- "name": "Reconciled Name",- "phone": "+1111111111",- },- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="restore_wins")-- # Backed-up properties restored, new properties preserved- assert result == {- "properties": {- "email": "[email protected]",- "name": "Original Name",- "phone": "+0987654321",- "new_prop_1": "added_after_backup",- "new_prop_2": "also_added_after",- "new_prop_3": "third_new_one",- },- "properties_last_updated_at": {- "email": "2024-01-01T00:00:00",- "name": "2024-01-01T00:00:00",- "new_prop_1": "2024-06-01T00:00:00",- },- "properties_last_operation": {- "email": "set_once",- "name": "set",- "new_prop_1": "set",- },- }-- def test_keep_newer_many_properties(self):- """Test keep_newer with many properties - restore unchanged, keep changed."""- current_person = {- "properties": {- # Unchanged since backup (current == after) - should restore- "prop_unchanged_1": "reconciled_value_1",- "prop_unchanged_2": "reconciled_value_2",- "prop_unchanged_3": "reconciled_value_3",- # Changed after backup (current != after) - should keep- "prop_changed_1": "user_changed_1",- "prop_changed_2": "user_changed_2",- "prop_changed_3": "user_changed_3",- # New properties not in backup - should keep- "new_prop_1": "brand_new_1",- "new_prop_2": "brand_new_2",- "new_prop_3": "brand_new_3",- },- "properties_last_updated_at": {- "prop_unchanged_1": "2024-06-01T00:00:00",- "prop_changed_1": "2024-06-01T00:00:00",- },- "properties_last_operation": {- "prop_unchanged_1": "set",- "prop_changed_1": "set",- },- }- backup_before = {- "properties": {- "prop_unchanged_1": "original_value_1",- "prop_unchanged_2": "original_value_2",- "prop_unchanged_3": "original_value_3",- "prop_changed_1": "original_changed_1",- "prop_changed_2": "original_changed_2",- "prop_changed_3": "original_changed_3",- },- "properties_last_updated_at": {- "prop_unchanged_1": "2024-01-01T00:00:00",- "prop_changed_1": "2024-01-01T00:00:00",- },- "properties_last_operation": {- "prop_unchanged_1": "set_once",- "prop_changed_1": "set_once",- },- }- backup_after = {- "properties": {- "prop_unchanged_1": "reconciled_value_1",- "prop_unchanged_2": "reconciled_value_2",- "prop_unchanged_3": "reconciled_value_3",- "prop_changed_1": "reconciled_changed_1",- "prop_changed_2": "reconciled_changed_2",- "prop_changed_3": "reconciled_changed_3",- },- "properties_last_updated_at": {},- "properties_last_operation": {},- }-- result = compute_restore_diff(current_person, backup_before, backup_after, conflict_resolution="keep_newer")-- # Only unchanged properties restored; changed and new properties kept- assert result == {- "properties": {- # Restored (current == after)- "prop_unchanged_1": "original_value_1",- "prop_unchanged_2": "original_value_2",- "prop_unchanged_3": "original_value_3",- # Kept (current != after)- "prop_changed_1": "user_changed_1",- "prop_changed_2": "user_changed_2",- "prop_changed_3": "user_changed_3",- # Kept (not in backup)- "new_prop_1": "brand_new_1",- "new_prop_2": "brand_new_2",- "new_prop_3": "brand_new_3",- },- "properties_last_updated_at": {- "prop_unchanged_1": "2024-01-01T00:00:00",- "prop_changed_1": "2024-06-01T00:00:00",- },- "properties_last_operation": {- "prop_unchanged_1": "set_once",- "prop_changed_1": "set",- },- }--[email protected]_db(transaction=True)-class TestRestoreIntegration:- """Integration tests for restore functionality using real database."""-- @pytest.fixture(autouse=True)- def setup_backup_table(self):- """Create the backup table if it doesn't exist."""- # Use persons database connection for backup table (since it references person_id)- with persons_db_connection(writer=True) as persons_conn, persons_conn.cursor() as cursor:- cursor.execute("""- CREATE TABLE IF NOT EXISTS posthog_person_reconciliation_backup (- job_id TEXT NOT NULL,- team_id INTEGER NOT NULL,- person_id BIGINT NOT NULL,- uuid UUID NOT NULL,- properties JSONB NOT NULL,- properties_last_updated_at JSONB,- properties_last_operation JSONB,- version BIGINT,- is_identified BOOLEAN NOT NULL,- created_at TIMESTAMP WITH TIME ZONE NOT NULL,- is_user_id INTEGER,- pending_operations JSONB NOT NULL,- properties_after JSONB,- properties_last_updated_at_after JSONB,- properties_last_operation_after JSONB,- version_after BIGINT,- backed_up_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- PRIMARY KEY (job_id, team_id, person_id)- )- """)-- @pytest.fixture- def organization(self):- """Create a test organization."""- return Organization.objects.create(name="Test Organization")-- @pytest.fixture- def team(self, organization):- """Create a test team."""- return Team.objects.create(organization=organization, name="Test Team")-- @pytest.fixture- def person(self, team):- """Create a test person."""- return create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=5,- )-- def test_fetch_backup_entries(self, team, person):- """Test fetching backup entries from database."""- job_id = f"test-job-{uuid_module.uuid4()}"-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- entries = fetch_backup_entries(cursor, job_id)-- assert len(entries) == 1- assert entries[0]["team_id"] == team.id- assert entries[0]["person_id"] == person.id- # JSONB may be string or dict depending on cursor type- props = entries[0]["properties"]- if isinstance(props, str):- props = json.loads(props)- assert props == {"email": "[email protected]"}-- def test_fetch_backup_entries_with_person_filter(self, team, person):- """Test fetching backup entries filtered by person_ids."""- job_id = f"test-job-{uuid_module.uuid4()}"-- person2 = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=1,- )-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person2.id,- person_uuid=str(person2.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- # Only fetch first person- entries = fetch_backup_entries(cursor, job_id, team_ids=None, person_ids=[person.id])-- assert len(entries) == 1- assert entries[0]["person_id"] == person.id-- def test_fetch_backup_entries_with_team_filter(self, organization, team, person):- """Test fetching backup entries filtered by team_ids."""- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create a second team with a person- team2 = Team.objects.create(organization=organization, name="Test Team 2")- person2 = create_person(- team_id=team2.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=1,- )-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- # Create backup entries for both teams- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )- create_backup_entry(- cursor,- job_id=job_id,- team_id=team2.id,- person_id=person2.id,- person_uuid=str(person2.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- # Only fetch first team- entries = fetch_backup_entries(cursor, job_id, team_ids=[team.id])-- assert len(entries) == 1- assert entries[0]["team_id"] == team.id- assert entries[0]["person_id"] == person.id-- def test_fetch_backup_entries_paginated(self, organization):- """Test paginated fetch with small batch size."""- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 2 teams with 5 persons each = 10 entries- team1 = Team.objects.create(organization=organization, name="Team 1")- team2 = Team.objects.create(organization=organization, name="Team 2")-- persons = []- for team in [team1, team2]:- for i in range(5):- p = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"p{i}@example.com"},- version=1,- )- persons.append((team.id, p))-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- # Create backup entries- for team_id, person in persons:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team_id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": f"[email protected]"},- )-- # Fetch with batch_size=3, should get 4 batches (3+3+3+1)- batches = list(fetch_backup_entries_paginated(cursor, job_id, batch_size=3))-- assert len(batches) == 4- assert len(batches[0]) == 3- assert len(batches[1]) == 3- assert len(batches[2]) == 3- assert len(batches[3]) == 1-- # All entries should be returned in order- all_entries = [e for batch in batches for e in batch]- assert len(all_entries) == 10-- # Should be ordered by (team_id, person_id)- for i in range(len(all_entries) - 1):- current = (all_entries[i]["team_id"], all_entries[i]["person_id"])- next_entry = (all_entries[i + 1]["team_id"], all_entries[i + 1]["person_id"])- assert current < next_entry, "Entries should be ordered by (team_id, person_id)"-- def test_fetch_backup_entries_paginated_respects_filters(self, organization):- """Test paginated fetch respects team_ids and person_ids filters."""- job_id = f"test-job-{uuid_module.uuid4()}"-- team1 = Team.objects.create(organization=organization, name="Team 1")- team2 = Team.objects.create(organization=organization, name="Team 2")-- persons: dict[int, list[Person]] = {}- for team in [team1, team2]:- persons[team.id] = []- for i in range(3):- p = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"p{i}@example.com"},- version=1,- )- persons[team.id].append(p)-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team_id, team_persons in persons.items():- for person in team_persons:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team_id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- # Filter by team_ids- batches = list(fetch_backup_entries_paginated(cursor, job_id, team_ids=[team1.id], batch_size=2))- all_entries = [e for batch in batches for e in batch]- assert len(all_entries) == 3- assert all(e["team_id"] == team1.id for e in all_entries)-- # Filter by person_ids- target_persons = [persons[team1.id][0].id, persons[team2.id][1].id]- batches = list(fetch_backup_entries_paginated(cursor, job_id, person_ids=target_persons, batch_size=1))- all_entries = [e for batch in batches for e in batch]- assert len(all_entries) == 2- assert all(e["person_id"] in target_persons for e in all_entries)-- def test_fetch_person_by_id(self, team, person):- """Test fetching person by id."""- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- fetched = fetch_person_by_id(cursor, team.id, person.id)-- assert fetched is not None- assert fetched["id"] == person.id- assert fetched["uuid"] == str(person.uuid)- assert fetched["properties"] == {"email": "[email protected]"}-- def test_fetch_persons_by_ids(self, team):- """Test batch fetching persons by ids."""- # Create multiple persons- persons = []- for i in range(5):- p = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"person{i}@example.com", "index": i},- version=i + 1,- )- persons.append(p)-- person_ids = [p.id for p in persons]-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- fetched = fetch_persons_by_ids(cursor, team.id, person_ids)-- assert len(fetched) == 5- for p in persons:- assert p.id in fetched- assert fetched[p.id]["uuid"] == str(p.uuid)- assert fetched[p.id]["properties"]["email"] == p.properties["email"]-- def test_fetch_persons_by_ids_partial(self, team):- """Test batch fetching when some ids don't exist."""- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=1,- )-- # Include non-existent ids- person_ids = [person.id, 99999, 99998]-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- fetched = fetch_persons_by_ids(cursor, team.id, person_ids)-- # Only the existing person should be returned- assert len(fetched) == 1- assert person.id in fetched- assert 99999 not in fetched- assert 99998 not in fetched-- def test_restore_full_overwrite(self, team, person):- """Test full_overwrite restore overwrites current state."""- job_id = f"test-job-{uuid_module.uuid4()}"-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]", "name": "Original"},- properties_after={"email": "[email protected]"},- version_before=4,- version_after=5,- )-- backup_entry = fetch_backup_entries(cursor, job_id)[0]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- backup_entry=backup_entry,- conflict_resolution="full_overwrite",- dry_run=False,- )-- assert success is True- assert person_data is not None-- refresh_person_from_persons_db(person)- assert person.properties == {"email": "[email protected]", "name": "Original"}- assert person.version == 6-- def test_restore_keep_newer(self, team, person):- """Test keep_newer restore preserves changed properties."""- job_id = f"test-job-{uuid_module.uuid4()}"-- # Set current state to match backup's "after" state for one property- person.properties = {"email": "[email protected]", "name": "User Changed This"}- save_person_to_persons_db(person)-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]", "name": "Original Name"},- properties_after={"email": "[email protected]", "name": "Reconciled Name"},- version_before=4,- version_after=5,- )-- backup_entry = fetch_backup_entries(cursor, job_id)[0]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- backup_entry=backup_entry,- conflict_resolution="keep_newer",- dry_run=False,- )-- assert success is True- assert person_data is not None-- refresh_person_from_persons_db(person)- # email: current == after, so restore to before- assert person.properties["email"] == "[email protected]"- # name: current != after (user changed it), so keep current- assert person.properties["name"] == "User Changed This"-- def test_restore_restore_wins(self, team, person):- """Test restore_wins restores all backed-up properties."""- job_id = f"test-job-{uuid_module.uuid4()}"-- person.properties = {"email": "[email protected]", "brand_new": "added_later"}- save_person_to_persons_db(person)-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- version_before=4,- version_after=5,- )-- backup_entry = fetch_backup_entries(cursor, job_id)[0]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- backup_entry=backup_entry,- conflict_resolution="restore_wins",- dry_run=False,- )-- assert success is True- assert person_data is not None-- refresh_person_from_persons_db(person)- # email should be restored to original- assert person.properties["email"] == "[email protected]"- # brand_new property added after backup should be preserved- assert person.properties["brand_new"] == "added_later"-- def test_restore_dry_run_does_not_modify(self, team, person):- """Test dry run mode doesn't modify the person."""- job_id = f"test-job-{uuid_module.uuid4()}"- original_properties = dict(person.properties)- original_version = person.version-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- backup_entry = fetch_backup_entries(cursor, job_id)[0]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- backup_entry=backup_entry,- conflict_resolution="full_overwrite",- dry_run=True,- )-- assert success is True- assert person_data is None # No data for Kafka in dry run-- refresh_person_from_persons_db(person)- assert person.properties == original_properties- assert person.version == original_version-- def test_restore_skips_when_no_changes_needed(self, team, person):- """Test restore returns success with no data when current matches backup."""- job_id = f"test-job-{uuid_module.uuid4()}"-- # Set current to match backup's before state- person.properties = {"email": "[email protected]"}- save_person_to_persons_db(person)-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- backup_entry = fetch_backup_entries(cursor, job_id)[0]-- success, person_data = restore_person_with_version_check(- cursor=cursor,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- backup_entry=backup_entry,- conflict_resolution="full_overwrite",- dry_run=False,- )-- assert success is True- assert person_data is None # No changes needed--[email protected]_db(transaction=True)-class TestRestoreJobEndToEnd:- """End-to-end tests for the full Dagster job execution."""-- @pytest.fixture(autouse=True)- def setup_backup_table(self):- """Create the backup table if it doesn't exist."""- with persons_db_connection(writer=True) as persons_conn, persons_conn.cursor() as cursor:- cursor.execute("""- CREATE TABLE IF NOT EXISTS posthog_person_reconciliation_backup (- job_id TEXT NOT NULL,- team_id INTEGER NOT NULL,- person_id BIGINT NOT NULL,- uuid UUID NOT NULL,- properties JSONB NOT NULL,- properties_last_updated_at JSONB,- properties_last_operation JSONB,- version BIGINT,- is_identified BOOLEAN NOT NULL,- created_at TIMESTAMP WITH TIME ZONE NOT NULL,- is_user_id INTEGER,- pending_operations JSONB NOT NULL,- properties_after JSONB,- properties_last_updated_at_after JSONB,- properties_last_operation_after JSONB,- version_after BIGINT,- backed_up_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- PRIMARY KEY (job_id, team_id, person_id)- )- """)-- @pytest.fixture- def organization(self):- """Create a test organization."""- return Organization.objects.create(name="Test Organization")-- @pytest.fixture- def team(self, organization):- """Create a test team."""- return Team.objects.create(organization=organization, name="Test Team")-- @pytest.fixture- def mock_kafka_producer(self):- """Create a mock Kafka producer."""- from unittest.mock import MagicMock-- producer = MagicMock()- producer.flush = MagicMock()- return producer-- def test_full_job_restores_persons(self, team, mock_kafka_producer, cluster):- """Test that the full Dagster job restores persons correctly."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create test persons- person1 = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]", "name": "Current Name"},- version=5,- )- person2 = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=3,- )-- # Create backup entries- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person1.id,- person_uuid=str(person1.uuid),- properties_before={"email": "[email protected]", "name": "Original Name"},- properties_after={"email": "[email protected]", "name": "Current Name"},- version_before=4,- version_after=5,- )- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person2.id,- person_uuid=str(person2.uuid),- properties_before={"email": "[email protected]", "extra": "prop"},- properties_after={"email": "[email protected]"},- version_before=2,- version_after=3,- )-- # Run the job- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify persons were restored- refresh_person_from_persons_db(person1)- refresh_person_from_persons_db(person2)-- assert person1.properties == {"email": "[email protected]", "name": "Original Name"}- assert person1.version == 6-- assert person2.properties == {"email": "[email protected]", "extra": "prop"}- assert person2.version == 4-- # Verify Kafka was called for each restored person- assert mock_kafka_producer.produce.call_count == 2- mock_kafka_producer.flush.assert_called()-- def test_full_job_with_team_filter(self, organization, team, mock_kafka_producer, cluster):- """Test that team_ids filter works in the full job."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create a second team- team2 = Team.objects.create(organization=organization, name="Test Team 2")-- # Create persons in both teams- person1 = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=2,- )- person2 = create_person(- team_id=team2.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=2,- )-- # Create backup entries for both- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person1.id,- person_uuid=str(person1.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )- create_backup_entry(- cursor,- job_id=job_id,- team_id=team2.id,- person_id=person2.id,- person_uuid=str(person2.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- # Run the job with team_ids filter - only restore team 1- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": [team.id],- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": [team.id],- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify only team 1 person was restored- refresh_person_from_persons_db(person1)- refresh_person_from_persons_db(person2)-- assert person1.properties == {"email": "[email protected]"}- assert person2.properties == {"email": "[email protected]"} # Unchanged-- def test_full_job_dry_run(self, team, mock_kafka_producer, cluster):- """Test that dry_run mode doesn't modify data."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": "[email protected]"},- version=5,- )- original_properties = dict(person.properties)- original_version = person.version-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": "[email protected]"},- properties_after={"email": "[email protected]"},- )-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": True,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": True,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify person was NOT modified- refresh_person_from_persons_db(person)- assert person.properties == original_properties- assert person.version == original_version-- # Verify Kafka was NOT called- mock_kafka_producer.produce.assert_not_called()-- def test_full_job_many_teams_and_persons_restore_all(self, organization, mock_kafka_producer, cluster):- """Test restoring all persons across many teams - verify data isolation."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 5 teams with 4 persons each = 20 persons total- teams = []- persons: dict[int, list[Person]] = {}-- for t in range(5):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(4):- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={- "email": f"current_t{t}_p{p}@example.com",- "team_marker": f"team_{t}",- "person_marker": f"person_{p}",- },- version=10 + p,- )- persons[team.id].append(person)-- # Create backup entries with distinct "before" data- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={- "email": f"original_t{t}_p{p}@example.com",- "team_marker": f"team_{t}",- "person_marker": f"person_{p}",- "restored": True,- },- properties_after={- "email": f"current_t{t}_p{p}@example.com",- "team_marker": f"team_{t}",- "person_marker": f"person_{p}",- },- version_before=9 + p,- version_after=10 + p,- )-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify ALL 20 persons were restored with correct data- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- assert person.properties == {- "email": f"original_t{t}_p{p}@example.com",- "team_marker": f"team_{t}",- "person_marker": f"person_{p}",- "restored": True,- }, f"Person t{t}_p{p} has wrong properties: {person.properties}"- assert person.version == 11 + p, f"Person t{t}_p{p} has wrong version: {person.version}"-- # Verify Kafka was called for all 20 persons- assert mock_kafka_producer.produce.call_count == 20-- def test_full_job_many_teams_filter_some_teams(self, organization, mock_kafka_producer, cluster):- """Test filtering to specific teams - only those teams should be restored."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 5 teams with 3 persons each- teams = []- persons: dict[int, list[Person]] = {}-- for t in range(5):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(3):- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"current_t{t}_p{p}@example.com", "status": "current"},- version=5,- )- persons[team.id].append(person)-- # Create backup entries for all- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": f"original_t{t}_p{p}@example.com", "status": "restored"},- properties_after={"email": f"current_t{t}_p{p}@example.com", "status": "current"},- )-- # Only restore teams 1 and 3 (indices)- teams_to_restore = [teams[1].id, teams[3].id]-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify teams 1 and 3 were restored- for t_idx in [1, 3]:- team = teams[t_idx]- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- assert person.properties["status"] == "restored", f"Team {t_idx} person {p} should be restored"- assert person.properties["email"] == f"original_t{t_idx}_p{p}@example.com"-- # Verify teams 0, 2, 4 were NOT restored- for t_idx in [0, 2, 4]:- team = teams[t_idx]- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- assert person.properties["status"] == "current", f"Team {t_idx} person {p} should NOT be restored"- assert person.properties["email"] == f"current_t{t_idx}_p{p}@example.com"-- # Verify Kafka was called for 6 persons (2 teams * 3 persons)- assert mock_kafka_producer.produce.call_count == 6-- def test_full_job_filter_some_persons(self, organization, mock_kafka_producer, cluster):- """Test filtering to specific person_ids - only those persons should be restored."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 3 teams with 5 persons each- teams = []- persons: dict[int, list[Person]] = {}- all_persons: list[Person] = []-- for t in range(3):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(5):- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"current_t{t}_p{p}@example.com", "restored": False},- version=5,- )- persons[team.id].append(person)- all_persons.append(person)-- # Create backup entries for all- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": f"original_t{t}_p{p}@example.com", "restored": True},- properties_after={"email": f"current_t{t}_p{p}@example.com", "restored": False},- )-- # Only restore specific persons: first person from each team + last person from team 0- persons_to_restore = [- persons[teams[0].id][0].id, # team 0, person 0- persons[teams[0].id][4].id, # team 0, person 4- persons[teams[1].id][0].id, # team 1, person 0- persons[teams[2].id][0].id, # team 2, person 0- ]-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify only the selected persons were restored- for person in all_persons:- refresh_person_from_persons_db(person)- if person.id in persons_to_restore:- assert person.properties["restored"] is True, f"Person {person.id} should be restored"- else:- assert person.properties["restored"] is False, f"Person {person.id} should NOT be restored"-- # Verify Kafka was called for 4 persons- assert mock_kafka_producer.produce.call_count == 4-- def test_full_job_filter_teams_and_persons(self, organization, mock_kafka_producer, cluster):- """Test filtering by both team_ids AND person_ids simultaneously."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 4 teams with 4 persons each = 16 persons- teams = []- persons: dict[int, list[Person]] = {}-- for t in range(4):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(4):- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={- "email": f"current_t{t}_p{p}@example.com",- "team_id": t,- "person_id": p,- "restored": False,- },- version=5,- )- persons[team.id].append(person)-- # Create backup entries for all- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={- "email": f"original_t{t}_p{p}@example.com",- "team_id": t,- "person_id": p,- "restored": True,- },- properties_after={- "email": f"current_t{t}_p{p}@example.com",- "team_id": t,- "person_id": p,- "restored": False,- },- )-- # Filter to teams 0 and 2, AND persons 1 and 3 within those teams- # This should restore: team0/person1, team0/person3, team2/person1, team2/person3- teams_to_restore = [teams[0].id, teams[2].id]- persons_to_restore = [- persons[teams[0].id][1].id,- persons[teams[0].id][3].id,- persons[teams[2].id][1].id,- persons[teams[2].id][3].id,- ]-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "team_ids": teams_to_restore,- "person_ids": persons_to_restore,- "conflict_resolution": "full_overwrite",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify exactly the right persons were restored- expected_restored = {- (0, 1): True,- (0, 3): True,- (2, 1): True,- (2, 3): True,- }-- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- should_restore = expected_restored.get((t, p), False)-- if should_restore:- assert person.properties["restored"] is True, f"t{t}_p{p} should be restored"- assert person.properties["email"] == f"original_t{t}_p{p}@example.com"- else:- assert person.properties["restored"] is False, f"t{t}_p{p} should NOT be restored"- assert person.properties["email"] == f"current_t{t}_p{p}@example.com"-- # Verify Kafka was called for 4 persons- assert mock_kafka_producer.produce.call_count == 4-- def test_full_job_restore_wins_preserves_new_properties(self, organization, mock_kafka_producer, cluster):- """Test restore_wins mode with many persons - new properties should be preserved."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 3 teams with 3 persons each- teams = []- persons: dict[int, list[Person]] = {}-- for t in range(3):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(3):- # Current state has properties added after backup- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={- "email": f"current_t{t}_p{p}@example.com",- "name": f"Current Name {t}_{p}",- "new_after_backup": f"new_value_t{t}_p{p}", # Added after backup- },- version=5,- )- persons[team.id].append(person)-- # Create backup entries - "before" doesn't have new_after_backup- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={- "email": f"original_t{t}_p{p}@example.com",- "name": f"Original Name {t}_{p}",- },- properties_after={- "email": f"current_t{t}_p{p}@example.com",- "name": f"Current Name {t}_{p}",- },- )-- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "restore_wins",- "dry_run": False,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "restore_wins",- "dry_run": False,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify all persons have:- # - email and name restored to original- # - new_after_backup preserved- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- assert person.properties == {- "email": f"original_t{t}_p{p}@example.com",- "name": f"Original Name {t}_{p}",- "new_after_backup": f"new_value_t{t}_p{p}", # Preserved!- }, f"Person t{t}_p{p} has wrong properties: {person.properties}"-- # All 9 persons restored- assert mock_kafka_producer.produce.call_count == 9-- def test_full_job_with_small_batch_size(self, organization, mock_kafka_producer, cluster):- """Test that batching works correctly with small batch sizes."""- from posthog.dags.person_property_reconciliation_restore import (- person_property_reconciliation_restore_from_backup,- )-- job_id = f"test-job-{uuid_module.uuid4()}"-- # Create 3 teams with 2, 2, 1 persons = 5 total- # With batch_size=2, this gives 3 batches (2, 2, 1) - last batch not full- teams = []- persons: dict[int, list[Person]] = {}- persons_per_team = [2, 2, 1]-- for t in range(3):- team = Team.objects.create(organization=organization, name=f"Team {t}")- teams.append(team)- persons[team.id] = []-- for p in range(persons_per_team[t]):- person = create_person(- team_id=team.id,- uuid=uuid_module.uuid4(),- properties={"email": f"current_t{t}_p{p}@example.com"},- version=5,- )- persons[team.id].append(person)-- with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- create_backup_entry(- cursor,- job_id=job_id,- team_id=team.id,- person_id=person.id,- person_uuid=str(person.uuid),- properties_before={"email": f"original_t{t}_p{p}@example.com", "restored": True},- properties_after={"email": f"current_t{t}_p{p}@example.com"},- )-- # Run with batch_size=2 to test pagination (3 batches: 2, 2, 1)- with persons_db_connection(writer=True) as persons_conn:- result = person_property_reconciliation_restore_from_backup.execute_in_process(- run_config={- "ops": {- "get_backup_entries_by_team": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- "backup_batch_size": 2,- }- },- "restore_team_chunk": {- "config": {- "job_id": job_id,- "conflict_resolution": "full_overwrite",- "dry_run": False,- "backup_batch_size": 2,- }- },- }- },- resources={- "cluster": cluster,- "persons_database": persons_conn,- "kafka_producer": mock_kafka_producer,- },- )-- assert result.success-- # Verify all 5 persons were restored correctly- for team in teams:- t = teams.index(team)- for p, person in enumerate(persons[team.id]):- refresh_person_from_persons_db(person)- assert person.properties == {- "email": f"original_t{t}_p{p}@example.com",- "restored": True,- }, f"Person t{t}_p{p} has wrong properties"-- # All 5 persons restored- assert mock_kafka_producer.produce.call_count == 5diff --git a/posthog/dags/tests/test_persondistinctids_without_person_cleanup.py b/posthog/dags/tests/test_persondistinctids_without_person_cleanup.pydeleted file mode 100644index 7ed4f9520a18..000000000000--- a/posthog/dags/tests/test_persondistinctids_without_person_cleanup.py+++ /dev/null@@ -1,779 +0,0 @@-"""Tests for the posthog_persons without distinct_ids in posthog_persondistinctid cleanup job."""--from unittest.mock import MagicMock, patch--import psycopg2-from dagster import build_op_context--from posthog.dags.persondistinctids_without_person_cleanup import (- PersonsDistinctIdsNoPersonCleanupConfig,- create_chunks_for_pdwp,- get_id_range_for_pdwp,- scan_delete_chunk_for_pdwp,-)---class MockPsycopg2Error(psycopg2.Error):- """Mock psycopg2.Error that allows setting pgcode."""-- def __init__(self, message: str, pgcode: str):- super().__init__(message)- # Store pgcode in a private attribute- self._pgcode = pgcode-- @property- def pgcode(self) -> str:- """Override pgcode property to return our custom value."""- return self._pgcode---def create_mock_psycopg2_error(message: str, pgcode: str) -> Exception:- """Create a mock psycopg2.Error with a specific pgcode."""- return MockPsycopg2Error(message, pgcode)---class TestCreateChunksForPdwp:- """Test the create_chunks_for_pdwp function."""-- def test_create_chunks_produces_non_overlapping_ranges(self):- """Test that chunks produce non-overlapping ranges."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- id_range = (1, 5000) # min_id=1, max_id=5000-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Verify no overlaps- for i, (min1, max1) in enumerate(chunk_ranges):- for j, (min2, max2) in enumerate(chunk_ranges):- if i != j:- # Chunks should not overlap- assert not (min1 <= min2 <= max1 or min1 <= max2 <= max1 or min2 <= min1 <= max2), (- f"Chunks overlap: ({min1}, {max1}) and ({min2}, {max2})"- )-- def test_create_chunks_covers_entire_id_space(self):- """Test that chunks cover the entire ID space from min to max."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Find the overall min and max covered- all_ids_covered: set[int] = set()- for chunk_min, chunk_max in chunk_ranges:- all_ids_covered.update(range(chunk_min, chunk_max + 1))-- # Verify all IDs from min_id to max_id are covered- expected_ids = set(range(min_id, max_id + 1))- assert all_ids_covered == expected_ids, (- f"Missing IDs: {expected_ids - all_ids_covered}, Extra IDs: {all_ids_covered - expected_ids}"- )-- def test_create_chunks_first_chunk_includes_max_id(self):- """Test that the first chunk (in yielded order) includes the source table max_id."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- # First chunk in the list (yielded first, highest IDs)- first_chunk_min, first_chunk_max = chunks[0].value-- assert first_chunk_max == max_id, f"First chunk max ({first_chunk_max}) should equal source max_id ({max_id})"- assert first_chunk_min <= max_id <= first_chunk_max, (- f"First chunk ({first_chunk_min}, {first_chunk_max}) should include max_id ({max_id})"- )-- def test_create_chunks_final_chunk_includes_min_id(self):- """Test that the final chunk (in yielded order) includes the source table min_id."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- # Last chunk in the list (yielded last, lowest IDs)- final_chunk_min, final_chunk_max = chunks[-1].value-- assert final_chunk_min == min_id, f"Final chunk min ({final_chunk_min}) should equal source min_id ({min_id})"- assert final_chunk_min <= min_id <= final_chunk_max, (- f"Final chunk ({final_chunk_min}, {final_chunk_max}) should include min_id ({min_id})"- )-- def test_create_chunks_reverse_order(self):- """Test that chunks are yielded in reverse order (highest IDs first)."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- # Verify chunks are in descending order by max_id- for i in range(len(chunks) - 1):- current_max = chunks[i].value[1]- next_max = chunks[i + 1].value[1]- assert current_max > next_max, (- f"Chunks not in reverse order: chunk {i} max ({current_max}) should be > chunk {i + 1} max ({next_max})"- )-- def test_create_chunks_exact_multiple(self):- """Test chunk creation when ID range is an exact multiple of chunk_size."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000 # Exactly 5 chunks of 1000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- assert len(chunks) == 5, f"Expected 5 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs)- assert chunks[0].value == (4001, 5000), f"First chunk should be (4001, 5000), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_non_exact_multiple(self):- """Test chunk creation when ID range is not an exact multiple of chunk_size."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 3750 # 3 full chunks + 1 partial chunk- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- assert len(chunks) == 4, f"Expected 4 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs) - should be the partial chunk- assert chunks[0].value == (3001, 3750), f"First chunk should be (3001, 3750), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_single_chunk(self):- """Test chunk creation when ID range fits in a single chunk."""- config = PersonsDistinctIdsNoPersonCleanupConfig(chunk_size=1000)- min_id, max_id = 100, 500- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pdwp(context, config, id_range))-- assert len(chunks) == 1, f"Expected 1 chunk, got {len(chunks)}"- assert chunks[0].value == (100, 500), f"Chunk should be (100, 500), got {chunks[0].value}"- assert chunks[0].value[0] == min_id and chunks[0].value[1] == max_id---def create_mock_database_resource(rowcount_values=None, fetchall_results=None):- """- Create a mock database resource that mimics psycopg2.extensions.connection.-- Args:- rowcount_values: List of rowcount values to return per DELETE call.- If None, defaults to 0. If a single int, uses that for all calls.- fetchall_results: List of results to return from fetchall() calls (for SELECT queries).- Each result should be a list of dict-like objects with "id" key.- If None, defaults to empty list.- """- mock_cursor = MagicMock()- if rowcount_values is None:- mock_cursor.rowcount = 0- elif isinstance(rowcount_values, int):- mock_cursor.rowcount = rowcount_values- else:- # Use side_effect to return different rowcounts per call- call_count = [0]-- def get_rowcount():- if call_count[0] < len(rowcount_values):- result = rowcount_values[call_count[0]]- call_count[0] += 1- return result- return rowcount_values[-1] if rowcount_values else 0-- mock_cursor.rowcount = property(lambda self: get_rowcount())-- mock_cursor.execute = MagicMock()- mock_cursor.fetchone = MagicMock()-- # Setup fetchall to return scan results- if fetchall_results is None:- mock_cursor.fetchall = MagicMock(return_value=[])- elif isinstance(fetchall_results, list):- fetchall_call_count = [0]-- def get_fetchall_result():- if fetchall_call_count[0] < len(fetchall_results):- result = fetchall_results[fetchall_call_count[0]]- fetchall_call_count[0] += 1- return result- return fetchall_results[-1] if fetchall_results else []-- mock_cursor.fetchall = MagicMock(side_effect=get_fetchall_result)- else:- mock_cursor.fetchall = MagicMock(return_value=fetchall_results)-- # Make cursor() return a context manager- mock_conn = MagicMock()- mock_conn.cursor.return_value.__enter__ = MagicMock(return_value=mock_cursor)- mock_conn.cursor.return_value.__exit__ = MagicMock(return_value=False)-- return mock_conn---def create_mock_cluster_resource():- """Create a mock ClickhouseCluster resource."""- return MagicMock()---class TestScanDeleteChunkForPdwp:- """Test the scan_delete_chunk_for_pdwp function."""-- def test_scan_delete_chunk_single_batch_success(self):- """Test successful scan and delete of a single batch within a chunk."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100) # Single batch covers entire chunk-- # Create 50 IDs to delete (returned from DELETE...RETURNING)- ids_deleted = [{"id": i} for i in range(1, 51)]-- # Mock: fetchall returns the deleted IDs from DELETE...RETURNING- mock_db = create_mock_database_resource(- fetchall_results=[ids_deleted],- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pdwp- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_pdwp(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 100- assert result["records_deleted"] == 50-- # Verify SET statements called once (session-level, before loop)- set_statements = [- "SET application_name = 'delete_personsdistinctids_with_no_person'",- "SET lock_timeout = '5s'",- "SET statement_timeout = '30min'",- "SET work_mem = '512MB'",- "SET temp_buffers = '512MB'",- "SET max_parallel_workers_per_gather = 2",- "SET max_parallel_maintenance_workers = 2",- "SET synchronous_commit = off",- ]-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Check SET statements were called- for stmt in set_statements:- assert any(stmt in call for call in execute_calls), f"SET statement not found: {stmt}"-- # Verify BEGIN and COMMIT called (single transaction with DELETE...RETURNING)- assert execute_calls.count("BEGIN") >= 1- assert execute_calls.count("COMMIT") >= 1-- # Verify DELETE...RETURNING query format- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_persondistinctid" in call]- assert len(delete_calls) == 1- delete_query = delete_calls[0]- assert "DELETE FROM posthog_persondistinctid" in delete_query- assert "WHERE pd.id >=" in delete_query- assert "AND pd.id <=" in delete_query- assert "NOT EXISTS" in delete_query- assert "RETURNING pd.id" in delete_query-- def test_scan_delete_chunk_multiple_batches(self):- """Test scan and delete with multiple batches in a chunk."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 250) # 3 batches: (1,100), (101,200), (201,250)-- # Create IDs deleted for each batch (returned from DELETE...RETURNING)- # Batch 1: 50 IDs, Batch 2: 75 IDs, Batch 3: 25 IDs- fetchall_results = [- [{"id": i} for i in range(1, 51)], # 50 IDs from first batch- [{"id": i} for i in range(101, 176)], # 75 IDs from second batch- [{"id": i} for i in range(201, 226)], # 25 IDs from third batch- ]-- mock_db = create_mock_database_resource(- fetchall_results=fetchall_results,- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pdwp- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_pdwp(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 250- assert result["records_deleted"] == 150 # 50 + 75 + 25 = 150-- # Verify SET statements called once (before loop)- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify BEGIN/COMMIT called 3 times (one per batch with DELETE...RETURNING)- assert execute_calls.count("BEGIN") >= 3- assert execute_calls.count("COMMIT") >= 3-- # Verify DELETE...RETURNING called 3 times (one per batch)- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_persondistinctid" in call]- assert len(delete_calls) == 3-- def test_scan_delete_chunk_serialization_failure_retry(self):- """Test that serialization failure triggers retry."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- # Create IDs to delete- ids_deleted = [{"id": i} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_deleted])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track DELETE query attempts- delete_attempts = [0]-- # First DELETE query raises SerializationFailure, second succeeds- def execute_side_effect(query, *args):- if "DELETE FROM posthog_persondistinctid" in query:- delete_attempts[0] += 1- if delete_attempts[0] == 1:- # First attempt raises error- error = create_mock_psycopg2_error("could not serialize access due to concurrent update", "40001")- raise error- # Second attempt succeeds - fetchall will return the IDs-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Need to patch time.sleep and run.job_name- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.persondistinctids_without_person_cleanup.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_pdwp(context, config, chunk)-- # Verify ROLLBACK was called on error- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- # Verify retry succeeded (should have DELETE called twice - once failed, once succeeded)- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_persondistinctid" in call]- assert len(delete_calls) >= 2 # At least one failed attempt and one successful-- def test_scan_delete_chunk_deadlock_retry(self):- """Test that deadlock triggers retry."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- # Create IDs to delete- ids_deleted = [{"id": i} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_deleted])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track DELETE query attempts- delete_attempts = [0]-- # First DELETE query raises deadlock, second succeeds- def execute_side_effect(query, *args):- if "DELETE FROM posthog_persondistinctid" in query:- delete_attempts[0] += 1- if delete_attempts[0] == 1:- # First attempt raises error- error = create_mock_psycopg2_error("deadlock detected", "40P01")- raise error- # Second attempt succeeds - fetchall will return the IDs-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Need to patch time.sleep and run.job_name- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.persondistinctids_without_person_cleanup.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_pdwp(context, config, chunk)-- # Verify ROLLBACK was called on error- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- # Verify retry succeeded (should have DELETE called twice - once failed, once succeeded)- delete_calls = [call for call in execute_calls if "DELETE FROM posthog_persondistinctid" in call]- assert len(delete_calls) >= 2 # At least one failed attempt and one successful-- def test_scan_delete_chunk_error_handling_and_rollback(self):- """Test error handling and rollback on non-retryable errors."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- # Create IDs to delete- ids_deleted = [{"id": i} for i in range(1, 51)]- mock_db = create_mock_database_resource(fetchall_results=[ids_deleted])- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Raise generic error on DELETE query (non-retryable error)- def execute_side_effect(query, *args):- if "DELETE FROM posthog_persondistinctid" in query:- raise Exception("Connection lost")-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- # Should raise Dagster.Failure- from dagster import Failure-- try:- scan_delete_chunk_for_pdwp(context, config, chunk)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- # Verify error metadata- assert e.description is not None- assert "Failed to scan and delete rows in batch" in e.description-- # Verify ROLLBACK was called- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- def test_scan_delete_chunk_query_format(self):- """Test that DELETE...RETURNING query has correct format."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- # Create IDs deleted (returned from DELETE...RETURNING)- ids_deleted = [{"id": i} for i in range(1, 11)] # 10 IDs- mock_db = create_mock_database_resource(- fetchall_results=[ids_deleted],- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pdwp- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_pdwp(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Find DELETE...RETURNING query- delete_query = next((call for call in execute_calls if "DELETE FROM posthog_persondistinctid" in call), None)- assert delete_query is not None-- # Verify DELETE...RETURNING query components- assert "DELETE FROM posthog_persondistinctid pd" in delete_query- assert "WHERE pd.id >=" in delete_query- assert "AND pd.id <=" in delete_query- assert "NOT EXISTS" in delete_query- assert "RETURNING pd.id" in delete_query-- def test_scan_delete_chunk_session_settings_applied_once(self):- """Test that SET statements are applied once at session level before batch loop."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=1000,- batch_size=50,- )- chunk = (1, 150) # 3 scan batches-- # Create IDs to delete for each scan batch- fetchall_results = [- [{"id": i} for i in range(1, 26)], # 25 IDs from first scan batch- [{"id": i} for i in range(51, 76)], # 25 IDs from second scan batch- [{"id": i} for i in range(101, 126)], # 25 IDs from third scan batch- ]- mock_db = create_mock_database_resource(- rowcount_values=25,- fetchall_results=fetchall_results,- )- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pdwp- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_pdwp(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Count SET statements (should be called once each, before loop)- set_statements = [- "SET application_name",- "SET lock_timeout",- "SET statement_timeout",- "SET work_mem",- "SET temp_buffers",- "SET max_parallel_workers_per_gather",- "SET max_parallel_maintenance_workers",- "SET synchronous_commit",- ]-- for stmt in set_statements:- count = sum(1 for call in execute_calls if stmt in call)- assert count == 1, f"Expected {stmt} to be called once, but it was called {count} times"-- # Verify SET statements come before BEGIN statements- set_indices = [i for i, call in enumerate(execute_calls) if any(stmt in call for stmt in set_statements)]- begin_indices = [i for i, call in enumerate(execute_calls) if call == "BEGIN"]-- if set_indices and begin_indices:- assert max(set_indices) < min(begin_indices), "SET statements should come before BEGIN statements"---class TestGetIdRangeForPdwp:- """Test the get_id_range_for_pdwp function."""-- def test_get_id_range_uses_min_id_override(self):- """Test that min_id override is honored when provided."""- config = PersonsDistinctIdsNoPersonCleanupConfig(min_id=100, max_id=None)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"max_id": 5000}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pdwp(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used-- # Verify min_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"-- # Verify max_id query WAS executed (queries posthog_person)- max_queries = [call for call in execute_calls if "MAX(id)" in call and "posthog_person" in call]- assert len(max_queries) == 1, "Should query for max_id from posthog_person when override is not provided"-- def test_get_id_range_uses_max_id_override(self):- """Test that max_id override is honored when provided."""- config = PersonsDistinctIdsNoPersonCleanupConfig(min_id=1, max_id=5000)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pdwp(context, config)-- assert result == (1, 5000)- assert result[1] == 5000 # max_id override used-- # Verify max_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- def test_get_id_range_uses_both_overrides(self):- """Test that both min_id and max_id overrides are honored when provided."""- config = PersonsDistinctIdsNoPersonCleanupConfig(min_id=100, max_id=5000)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pdwp(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used- assert result[1] == 5000 # max_id override used-- # Verify NO queries were executed (both overrides used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- def test_get_id_range_queries_database_when_max_id_not_provided(self):- """Test that database is queried for max_id when override is not provided."""- config = PersonsDistinctIdsNoPersonCleanupConfig(min_id=1, max_id=None)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"max_id": 5000}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pdwp(context, config)-- assert result == (1, 5000)-- # Verify max_id query was executed (queries posthog_person)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- max_queries = [call for call in execute_calls if "MAX(id)" in call and "posthog_person" in call]- assert len(max_queries) == 1, "Should query for max_id from posthog_person when override is not provided"-- def test_get_id_range_validates_max_id_greater_than_min_id(self):- """Test that validation fails when max_id < min_id."""- config = PersonsDistinctIdsNoPersonCleanupConfig(min_id=5000, max_id=100)- mock_db = create_mock_database_resource()-- context = build_op_context(resources={"database": mock_db})-- from dagster import Failure-- try:- get_id_range_for_pdwp(context, config)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- assert e.description is not None- description = e.description- assert "max_id" in description.lower() or "invalid" in description.lower()- assert "5000" in description or "100" in description---class TestMetricsPublishing:- """Test metrics publishing batching behavior."""-- def test_metrics_published_every_100_batches(self):- """Test that metrics are only published every 100 batches to reduce ClickHouse writes."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=50000,- batch_size=100,- )- # Create a chunk with 250 batches (25000 records)- chunk = (1, 25000)-- # Create fetchall results for all 250 batches- # Each batch deletes 10 records- fetchall_results = [[{"id": i} for i in range(batch_num * 10, batch_num * 10 + 10)] for batch_num in range(250)]-- mock_db = create_mock_database_resource(fetchall_results=fetchall_results)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )-- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job", run_id="test_run_id")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- scan_delete_chunk_for_pdwp(context, config, chunk)-- # Get the metrics client from the cluster- metrics_client = mock_cluster-- # Count how many times increment was called for batch metrics- increment_calls = [- call for call in metrics_client.method_calls if call[0] == "increment" or "increment" in str(call)- ]-- assert len(increment_calls) < 50, (- f"Expected metrics to be batched (~16 calls), but got {len(increment_calls)} increment calls"- )-- def test_metrics_flushed_at_chunk_end(self):- """Test that remaining accumulated metrics are flushed at the end of a chunk."""- config = PersonsDistinctIdsNoPersonCleanupConfig(- chunk_size=10000,- batch_size=100,- )- # Create a chunk with 50 batches (not a multiple of 100)- chunk = (1, 5000)-- # Create fetchall results for all 50 batches- fetchall_results = [[{"id": i} for i in range(batch_num * 10, batch_num * 10 + 10)] for batch_num in range(50)]-- mock_db = create_mock_database_resource(fetchall_results=fetchall_results)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )-- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job", run_id="test_run_id")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- result = scan_delete_chunk_for_pdwp(context, config, chunk)-- # Verify the chunk completed successfully- assert result["records_deleted"] == 500 # 50 batches × 10 records each-- metrics_client = mock_cluster- increment_calls = [- call for call in metrics_client.method_calls if call[0] == "increment" or "increment" in str(call)- ]-- # Should have final flush metrics- assert len(increment_calls) > 0, "Expected metrics to be flushed at chunk end"- assert len(increment_calls) < 20, f"Expected only final flush (~6 calls), got {len(increment_calls)}"diff --git a/posthog/dags/tests/test_persons_new_backfill.py b/posthog/dags/tests/test_persons_new_backfill.pydeleted file mode 100644index 1893e55724bf..000000000000--- a/posthog/dags/tests/test_persons_new_backfill.py+++ /dev/null@@ -1,604 +0,0 @@-"""Tests for the persons new backfill job."""--from unittest.mock import MagicMock, patch--import psycopg2.errors-from dagster import build_op_context--from posthog.dags.persons_new_backfill import (- PersonsNewBackfillConfig,- copy_chunk,- create_chunks_for_pnb,- get_id_range_for_pnb,-)---class TestCreateChunksForPnb:- """Test the create_chunks_for_pnb function."""-- def test_create_chunks_produces_non_overlapping_ranges(self):- """Test that chunks produce non-overlapping ranges."""- config = PersonsNewBackfillConfig(chunk_size=1000)- id_range = (1, 5000) # min_id=1, max_id=5000-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Verify no overlaps- for i, (min1, max1) in enumerate(chunk_ranges):- for j, (min2, max2) in enumerate(chunk_ranges):- if i != j:- # Chunks should not overlap- assert not (min1 <= min2 <= max1 or min1 <= max2 <= max1 or min2 <= min1 <= max2), (- f"Chunks overlap: ({min1}, {max1}) and ({min2}, {max2})"- )-- def test_create_chunks_covers_entire_id_space(self):- """Test that chunks cover the entire ID space from min to max."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Find the overall min and max covered- all_ids_covered: set[int] = set()- for chunk_min, chunk_max in chunk_ranges:- all_ids_covered.update(range(chunk_min, chunk_max + 1))-- # Verify all IDs from min_id to max_id are covered- expected_ids = set(range(min_id, max_id + 1))- assert all_ids_covered == expected_ids, (- f"Missing IDs: {expected_ids - all_ids_covered}, Extra IDs: {all_ids_covered - expected_ids}"- )-- def test_create_chunks_first_chunk_includes_max_id(self):- """Test that the first chunk (in yielded order) includes the source table max_id."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- # First chunk in the list (yielded first, highest IDs)- first_chunk_min, first_chunk_max = chunks[0].value-- assert first_chunk_max == max_id, f"First chunk max ({first_chunk_max}) should equal source max_id ({max_id})"- assert first_chunk_min <= max_id <= first_chunk_max, (- f"First chunk ({first_chunk_min}, {first_chunk_max}) should include max_id ({max_id})"- )-- def test_create_chunks_final_chunk_includes_min_id(self):- """Test that the final chunk (in yielded order) includes the source table min_id."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- # Last chunk in the list (yielded last, lowest IDs)- final_chunk_min, final_chunk_max = chunks[-1].value-- assert final_chunk_min == min_id, f"Final chunk min ({final_chunk_min}) should equal source min_id ({min_id})"- assert final_chunk_min <= min_id <= final_chunk_max, (- f"Final chunk ({final_chunk_min}, {final_chunk_max}) should include min_id ({min_id})"- )-- def test_create_chunks_reverse_order(self):- """Test that chunks are yielded in reverse order (highest IDs first)."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- # Verify chunks are in descending order by max_id- for i in range(len(chunks) - 1):- current_max = chunks[i].value[1]- next_max = chunks[i + 1].value[1]- assert current_max > next_max, (- f"Chunks not in reverse order: chunk {i} max ({current_max}) should be > chunk {i + 1} max ({next_max})"- )-- def test_create_chunks_exact_multiple(self):- """Test chunk creation when ID range is an exact multiple of chunk_size."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 5000 # Exactly 5 chunks of 1000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- assert len(chunks) == 5, f"Expected 5 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs)- assert chunks[0].value == (4001, 5000), f"First chunk should be (4001, 5000), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_non_exact_multiple(self):- """Test chunk creation when ID range is not an exact multiple of chunk_size."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 1, 3750 # 3 full chunks + 1 partial chunk- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- assert len(chunks) == 4, f"Expected 4 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs) - should be the partial chunk- assert chunks[0].value == (3001, 3750), f"First chunk should be (3001, 3750), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_single_chunk(self):- """Test chunk creation when ID range fits in a single chunk."""- config = PersonsNewBackfillConfig(chunk_size=1000)- min_id, max_id = 100, 500- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pnb(context, config, id_range))-- assert len(chunks) == 1, f"Expected 1 chunk, got {len(chunks)}"- assert chunks[0].value == (100, 500), f"Chunk should be (100, 500), got {chunks[0].value}"- assert chunks[0].value[0] == min_id and chunks[0].value[1] == max_id---def create_mock_database_resource(rowcount_values=None):- """- Create a mock database resource that mimics psycopg2.extensions.connection.-- Args:- rowcount_values: List of rowcount values to return per INSERT call.- If None, defaults to 0. If a single int, uses that for all calls.- """- mock_cursor = MagicMock()- if rowcount_values is None:- mock_cursor.rowcount = 0- elif isinstance(rowcount_values, int):- mock_cursor.rowcount = rowcount_values- else:- # Use side_effect to return different rowcounts per call- call_count = [0]-- def get_rowcount():- if call_count[0] < len(rowcount_values):- result = rowcount_values[call_count[0]]- call_count[0] += 1- return result- return rowcount_values[-1] if rowcount_values else 0-- mock_cursor.rowcount = property(lambda self: get_rowcount())-- mock_cursor.execute = MagicMock()-- # Make cursor() return a context manager- mock_conn = MagicMock()- mock_conn.cursor.return_value.__enter__ = MagicMock(return_value=mock_cursor)- mock_conn.cursor.return_value.__exit__ = MagicMock(return_value=False)-- return mock_conn---def create_mock_cluster_resource():- """Create a mock ClickhouseCluster resource."""- return MagicMock()---class TestCopyChunk:- """Test the copy_chunk function."""-- def test_copy_chunk_single_batch_success(self):- """Test successful copy of a single batch within a chunk."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=100, source_table="posthog_persons", destination_table="posthog_persons_new"- )- chunk = (1, 100) # Single batch covers entire chunk-- mock_db = create_mock_database_resource(rowcount_values=50)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in copy_chunk- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = copy_chunk(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 100- assert result["records_copied"] == 50-- # Verify SET statements called once (session-level, before loop)- set_statements = [- "SET application_name = 'backfill_posthog_persons_to_posthog_persons_new'",- "SET lock_timeout = '5s'",- "SET statement_timeout = '30min'",- "SET maintenance_work_mem = '12GB'",- "SET work_mem = '512MB'",- "SET temp_buffers = '512MB'",- "SET max_parallel_workers_per_gather = 2",- "SET max_parallel_maintenance_workers = 2",- "SET synchronous_commit = off",- ]-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Check SET statements were called- for stmt in set_statements:- assert any(stmt in call for call in execute_calls), f"SET statement not found: {stmt}"-- # Verify BEGIN, INSERT, COMMIT called once- assert execute_calls.count("BEGIN") == 1- assert execute_calls.count("COMMIT") == 1-- # Verify INSERT query format- insert_calls = [call for call in execute_calls if "INSERT INTO" in call]- assert len(insert_calls) == 1- insert_query = insert_calls[0]- assert "INSERT INTO posthog_persons_new" in insert_query- assert "SELECT s.*" in insert_query- assert "FROM posthog_persons s" in insert_query- assert "WHERE s.id >" in insert_query- assert "AND s.id <=" in insert_query- assert "NOT EXISTS" in insert_query- assert "ORDER BY s.id DESC" in insert_query-- def test_copy_chunk_multiple_batches(self):- """Test copy with multiple batches in a chunk."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=100, source_table="posthog_persons", destination_table="posthog_persons_new"- )- chunk = (1, 250) # 3 batches: (1,100), (100,200), (200,250)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- # Track rowcount per batch - use a list to track INSERT calls- rowcounts = [50, 75, 25]- insert_call_count = [0]-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track INSERT calls and set rowcount accordingly- def execute_with_rowcount(query, *args):- if "INSERT INTO" in query:- if insert_call_count[0] < len(rowcounts):- cursor.rowcount = rowcounts[insert_call_count[0]]- insert_call_count[0] += 1- else:- cursor.rowcount = 0-- cursor.execute.side_effect = execute_with_rowcount-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in copy_chunk- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = copy_chunk(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 250- assert result["records_copied"] == 150 # 50 + 75 + 25-- # Verify SET statements called once (before loop)- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify BEGIN/COMMIT called 3 times (one per batch)- assert execute_calls.count("BEGIN") == 3- assert execute_calls.count("COMMIT") == 3-- # Verify INSERT called 3 times- insert_calls = [call for call in execute_calls if "INSERT INTO" in call]- assert len(insert_calls) == 3-- def test_copy_chunk_duplicate_key_violation_retry(self):- """Test that duplicate key violation triggers retry."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=100, source_table="posthog_persons", destination_table="posthog_persons_new"- )- chunk = (1, 100)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track INSERT attempts- insert_attempts = [0]-- # First INSERT raises UniqueViolation, second succeeds- def execute_side_effect(query, *args):- if "INSERT INTO" in query:- insert_attempts[0] += 1- if insert_attempts[0] == 1:- # First INSERT attempt raises error- # Use real UniqueViolation - pgcode is readonly but isinstance check will pass- raise psycopg2.errors.UniqueViolation("duplicate key value violates unique constraint")- # Subsequent calls succeed- cursor.rowcount = 50 # Success on retry-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Need to patch time.sleep and run.job_name- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.persons_new_backfill.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- copy_chunk(context, config, chunk)-- # Verify ROLLBACK was called on error- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- # Verify retry succeeded (should have INSERT called twice, COMMIT once)- insert_calls = [call for call in execute_calls if "INSERT INTO" in call]- assert len(insert_calls) >= 1 # At least one successful INSERT-- def test_copy_chunk_error_handling_and_rollback(self):- """Test error handling and rollback on non-duplicate errors."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=100, source_table="posthog_persons", destination_table="posthog_persons_new"- )- chunk = (1, 100)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Raise generic error on INSERT- def execute_side_effect(query, *args):- if "INSERT INTO" in query:- raise Exception("Connection lost")-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in copy_chunk- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- # Should raise Dagster.Failure- from dagster import Failure-- try:- copy_chunk(context, config, chunk)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- # Verify error metadata- assert e.description is not None- assert "Failed to copy batch" in e.description-- # Verify ROLLBACK was called- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- def test_copy_chunk_insert_query_format(self):- """Test that INSERT query has correct format."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=100, source_table="test_source", destination_table="test_dest"- )- chunk = (1, 100)-- mock_db = create_mock_database_resource(rowcount_values=10)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in copy_chunk- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- copy_chunk(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Find INSERT query- insert_query = next((call for call in execute_calls if "INSERT INTO" in call), None)- assert insert_query is not None-- # Verify query components- assert "INSERT INTO test_dest" in insert_query- assert "SELECT s.*" in insert_query- assert "FROM test_source s" in insert_query- assert "WHERE s.id >" in insert_query- assert "AND s.id <=" in insert_query- assert "NOT EXISTS" in insert_query- assert "d.team_id = s.team_id" in insert_query- assert "d.id = s.id" in insert_query- assert "ORDER BY s.id DESC" in insert_query-- def test_copy_chunk_session_settings_applied_once(self):- """Test that SET statements are applied once at session level before batch loop."""- config = PersonsNewBackfillConfig(- chunk_size=1000, batch_size=50, source_table="posthog_persons", destination_table="posthog_persons_new"- )- chunk = (1, 150) # 3 batches-- mock_db = create_mock_database_resource(rowcount_values=25)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in copy_chunk- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- copy_chunk(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Count SET statements (should be called once each, before loop)- set_statements = [- "SET application_name",- "SET lock_timeout",- "SET statement_timeout",- "SET maintenance_work_mem",- "SET work_mem",- "SET temp_buffers",- "SET max_parallel_workers_per_gather",- "SET max_parallel_maintenance_workers",- "SET synchronous_commit",- ]-- for stmt in set_statements:- count = sum(1 for call in execute_calls if stmt in call)- assert count == 1, f"Expected {stmt} to be called once, but it was called {count} times"-- # Verify SET statements come before BEGIN statements- set_indices = [i for i, call in enumerate(execute_calls) if any(stmt in call for stmt in set_statements)]- begin_indices = [i for i, call in enumerate(execute_calls) if call == "BEGIN"]-- if set_indices and begin_indices:- assert max(set_indices) < min(begin_indices), "SET statements should come before BEGIN statements"---class TestGetIdRangeForPnb:- """Test the get_id_range_for_pnb function."""-- def test_get_id_range_uses_min_id_override(self):- """Test that min_id override is honored when provided."""- config = PersonsNewBackfillConfig(min_id=100, max_id=None, source_table="posthog_persons")- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"max_id": 5000}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pnb(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used-- # Verify min_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"-- # Verify max_id query WAS executed- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(max_queries) == 1, "Should query for max_id when override is not provided"-- def test_get_id_range_uses_max_id_override(self):- """Test that max_id override is honored when provided."""- config = PersonsNewBackfillConfig(min_id=None, max_id=5000, source_table="posthog_persons")- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"min_id": 1}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pnb(context, config)-- assert result == (1, 5000)- assert result[1] == 5000 # max_id override used-- # Verify max_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- # Verify min_id query WAS executed- min_queries = [call for call in execute_calls if "MIN(id)" in call]- assert len(min_queries) == 1, "Should query for min_id when override is not provided"-- def test_get_id_range_uses_both_overrides(self):- """Test that both min_id and max_id overrides are honored when provided."""- config = PersonsNewBackfillConfig(min_id=100, max_id=5000, source_table="posthog_persons")- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pnb(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used- assert result[1] == 5000 # max_id override used-- # Verify NO queries were executed (both overrides used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- def test_get_id_range_queries_database_when_no_overrides(self):- """Test that database is queried when no overrides are provided."""- config = PersonsNewBackfillConfig(min_id=None, max_id=None, source_table="posthog_persons")- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- # First call returns min_id, second call returns max_id- cursor.fetchone.side_effect = [{"min_id": 1}, {"max_id": 5000}]-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pnb(context, config)-- assert result == (1, 5000)-- # Verify both queries were executed- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(min_queries) == 1, "Should query for min_id when override is not provided"- assert len(max_queries) == 1, "Should query for max_id when override is not provided"-- def test_get_id_range_validates_max_id_greater_than_min_id(self):- """Test that validation fails when max_id < min_id."""- config = PersonsNewBackfillConfig(min_id=5000, max_id=100, source_table="posthog_persons")- mock_db = create_mock_database_resource()-- context = build_op_context(resources={"database": mock_db})-- from dagster import Failure-- try:- get_id_range_for_pnb(context, config)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- assert e.description is not None- description = e.description- assert "max_id" in description.lower() or "invalid" in description.lower()- assert "5000" in description or "100" in descriptiondiff --git a/posthog/dags/tests/test_persons_without_distinct_ids_cleanup.py b/posthog/dags/tests/test_persons_without_distinct_ids_cleanup.pydeleted file mode 100644index 4c81e708cb83..000000000000--- a/posthog/dags/tests/test_persons_without_distinct_ids_cleanup.py+++ /dev/null@@ -1,675 +0,0 @@-"""Tests for the posthog_persons without distinct_ids in posthog_persondistinctid cleanup job."""--from unittest.mock import MagicMock, patch--import psycopg2-from dagster import build_op_context--from posthog.dags.persons_without_distinct_ids_cleanup import (- PersonsNoDistinctIdsCleanupConfig,- create_chunks_for_pwdc,- get_id_range_for_pwdc,- scan_delete_chunk_for_pwdc,-)---class MockPsycopg2Error(psycopg2.Error):- """Mock psycopg2.Error that allows setting pgcode."""-- def __init__(self, message: str, pgcode: str):- super().__init__(message)- # Store pgcode in a private attribute- self._pgcode = pgcode-- @property- def pgcode(self) -> str:- """Override pgcode property to return our custom value."""- return self._pgcode---def create_mock_psycopg2_error(message: str, pgcode: str) -> Exception:- """Create a mock psycopg2.Error with a specific pgcode."""- return MockPsycopg2Error(message, pgcode)---class TestCreateChunksForPwdc:- """Test the create_chunks_for_pwdc function."""-- def test_create_chunks_produces_non_overlapping_ranges(self):- """Test that chunks produce non-overlapping ranges."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- id_range = (1, 5000) # min_id=1, max_id=5000-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Verify no overlaps- for i, (min1, max1) in enumerate(chunk_ranges):- for j, (min2, max2) in enumerate(chunk_ranges):- if i != j:- # Chunks should not overlap- assert not (min1 <= min2 <= max1 or min1 <= max2 <= max1 or min2 <= min1 <= max2), (- f"Chunks overlap: ({min1}, {max1}) and ({min2}, {max2})"- )-- def test_create_chunks_covers_entire_id_space(self):- """Test that chunks cover the entire ID space from min to max."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- # Extract all chunk ranges from DynamicOutput objects- chunk_ranges = [chunk.value for chunk in chunks]-- # Find the overall min and max covered- all_ids_covered: set[int] = set()- for chunk_min, chunk_max in chunk_ranges:- all_ids_covered.update(range(chunk_min, chunk_max + 1))-- # Verify all IDs from min_id to max_id are covered- expected_ids = set(range(min_id, max_id + 1))- assert all_ids_covered == expected_ids, (- f"Missing IDs: {expected_ids - all_ids_covered}, Extra IDs: {all_ids_covered - expected_ids}"- )-- def test_create_chunks_first_chunk_includes_max_id(self):- """Test that the first chunk (in yielded order) includes the source table max_id."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- # First chunk in the list (yielded first, highest IDs)- first_chunk_min, first_chunk_max = chunks[0].value-- assert first_chunk_max == max_id, f"First chunk max ({first_chunk_max}) should equal source max_id ({max_id})"- assert first_chunk_min <= max_id <= first_chunk_max, (- f"First chunk ({first_chunk_min}, {first_chunk_max}) should include max_id ({max_id})"- )-- def test_create_chunks_final_chunk_includes_min_id(self):- """Test that the final chunk (in yielded order) includes the source table min_id."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- # Last chunk in the list (yielded last, lowest IDs)- final_chunk_min, final_chunk_max = chunks[-1].value-- assert final_chunk_min == min_id, f"Final chunk min ({final_chunk_min}) should equal source min_id ({min_id})"- assert final_chunk_min <= min_id <= final_chunk_max, (- f"Final chunk ({final_chunk_min}, {final_chunk_max}) should include min_id ({min_id})"- )-- def test_create_chunks_reverse_order(self):- """Test that chunks are yielded in reverse order (highest IDs first)."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- # Verify chunks are in descending order by max_id- for i in range(len(chunks) - 1):- current_max = chunks[i].value[1]- next_max = chunks[i + 1].value[1]- assert current_max > next_max, (- f"Chunks not in reverse order: chunk {i} max ({current_max}) should be > chunk {i + 1} max ({next_max})"- )-- def test_create_chunks_exact_multiple(self):- """Test chunk creation when ID range is an exact multiple of chunk_size."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 5000 # Exactly 5 chunks of 1000- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- assert len(chunks) == 5, f"Expected 5 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs)- assert chunks[0].value == (4001, 5000), f"First chunk should be (4001, 5000), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_non_exact_multiple(self):- """Test chunk creation when ID range is not an exact multiple of chunk_size."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 1, 3750 # 3 full chunks + 1 partial chunk- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- assert len(chunks) == 4, f"Expected 4 chunks, got {len(chunks)}"-- # Verify first chunk (highest IDs) - should be the partial chunk- assert chunks[0].value == (3001, 3750), f"First chunk should be (3001, 3750), got {chunks[0].value}"-- # Verify last chunk (lowest IDs)- assert chunks[-1].value == (1, 1000), f"Last chunk should be (1, 1000), got {chunks[-1].value}"-- def test_create_chunks_single_chunk(self):- """Test chunk creation when ID range fits in a single chunk."""- config = PersonsNoDistinctIdsCleanupConfig(chunk_size=1000)- min_id, max_id = 100, 500- id_range = (min_id, max_id)-- context = build_op_context()- chunks = list(create_chunks_for_pwdc(context, config, id_range))-- assert len(chunks) == 1, f"Expected 1 chunk, got {len(chunks)}"- assert chunks[0].value == (100, 500), f"Chunk should be (100, 500), got {chunks[0].value}"- assert chunks[0].value[0] == min_id and chunks[0].value[1] == max_id---def create_mock_database_resource(rowcount_values=None):- """- Create a mock database resource that mimics psycopg2.extensions.connection.-- Args:- rowcount_values: List of rowcount values to return per INSERT call.- If None, defaults to 0. If a single int, uses that for all calls.- """- mock_cursor = MagicMock()- if rowcount_values is None:- mock_cursor.rowcount = 0- elif isinstance(rowcount_values, int):- mock_cursor.rowcount = rowcount_values- else:- # Use side_effect to return different rowcounts per call- call_count = [0]-- def get_rowcount():- if call_count[0] < len(rowcount_values):- result = rowcount_values[call_count[0]]- call_count[0] += 1- return result- return rowcount_values[-1] if rowcount_values else 0-- mock_cursor.rowcount = property(lambda self: get_rowcount())-- mock_cursor.execute = MagicMock()-- # Make cursor() return a context manager- mock_conn = MagicMock()- mock_conn.cursor.return_value.__enter__ = MagicMock(return_value=mock_cursor)- mock_conn.cursor.return_value.__exit__ = MagicMock(return_value=False)-- return mock_conn---def create_mock_cluster_resource():- """Create a mock ClickhouseCluster resource."""- return MagicMock()---class TestScanDeleteChunkForPwdc:- """Test the scan_delete_chunk_for_pwdc function."""-- def test_scan_delete_chunk_single_batch_success(self):- """Test successful scan and delete of a single batch within a chunk."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100) # Single batch covers entire chunk-- mock_db = create_mock_database_resource(rowcount_values=50)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pwdc- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_pwdc(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 100- assert result["records_deleted"] == 50-- # Verify SET statements called once (session-level, before loop)- set_statements = [- "SET application_name = 'delete_persons_with_no_distinct_ids'",- "SET lock_timeout = '5s'",- "SET statement_timeout = '30min'",- "SET maintenance_work_mem = '12GB'",- "SET work_mem = '512MB'",- "SET temp_buffers = '512MB'",- "SET max_parallel_workers_per_gather = 2",- "SET max_parallel_maintenance_workers = 2",- "SET synchronous_commit = off",- ]-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Check SET statements were called- for stmt in set_statements:- assert any(stmt in call for call in execute_calls), f"SET statement not found: {stmt}"-- # Verify BEGIN, INSERT, COMMIT called once- assert execute_calls.count("BEGIN") == 1- assert execute_calls.count("COMMIT") == 1-- # Verify INSERT query format- scan_delete_calls = [call for call in execute_calls if "DELETE FROM" in call]- assert len(scan_delete_calls) == 1- scan_delete_query = scan_delete_calls[0]- assert f"DELETE FROM {config.persons_table}" in scan_delete_query- assert "WHERE p.id >=" in scan_delete_query- assert "AND p.id <=" in scan_delete_query- assert "NOT EXISTS" in scan_delete_query- assert "ORDER BY p.id DESC" in scan_delete_query-- def test_scan_delete_chunk_multiple_batches(self):- """Test scan and delete with multiple batches in a chunk."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 250) # 3 batches: (1,100), (100,200), (200,250)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- # Track rowcount per batch - use a list to track INSERT calls- rowcounts = [50, 75, 25]- insert_call_count = [0]-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track INSERT calls and set rowcount accordingly- def execute_with_rowcount(query, *args):- if "DELETE FROM" in query:- if insert_call_count[0] < len(rowcounts):- cursor.rowcount = rowcounts[insert_call_count[0]]- insert_call_count[0] += 1- else:- cursor.rowcount = 0-- cursor.execute.side_effect = execute_with_rowcount-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pwdc- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- result = scan_delete_chunk_for_pwdc(context, config, chunk)-- # Verify result- assert result["chunk_min"] == 1- assert result["chunk_max"] == 250- assert result["records_deleted"] == 150 # 50 + 75 + 25-- # Verify SET statements called once (before loop)- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Verify BEGIN/COMMIT called 3 times (one per batch)- assert execute_calls.count("BEGIN") == 3- assert execute_calls.count("COMMIT") == 3-- # Verify INSERT called 3 times- insert_calls = [call for call in execute_calls if "DELETE FROM" in call]- assert len(insert_calls) == 3-- def test_scan_delete_chunk_serialization_failure_retry(self):- """Test that serialization failure triggers retry."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track DELETE attempts- scan_delete_attempts = [0]-- # First DELETE raises SerializationFailure, second succeeds- def execute_side_effect(query, *args):- if "DELETE FROM" in query:- scan_delete_attempts[0] += 1- if scan_delete_attempts[0] == 1:- # First DELETE attempt raises error- # Create a mock error with pgcode 40001 for serialization failure- error = create_mock_psycopg2_error("could not serialize access due to concurrent update", "40001")- raise error- # Subsequent calls succeed- cursor.rowcount = 50 # Success on retry-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Need to patch time.sleep and run.job_name- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.persons_without_distinct_ids_cleanup.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_pwdc(context, config, chunk)-- # Verify ROLLBACK was called on error- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- # Verify retry succeeded (should have DELETE called twice, COMMIT once)- scan_delete_calls = [call for call in execute_calls if "DELETE FROM" in call]- assert len(scan_delete_calls) >= 1 # At least one successful DELETE-- def test_scan_delete_chunk_deadlock_retry(self):- """Test that deadlock triggers retry."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Track DELETE attempts- scan_delete_attempts = [0]-- # First DELETE raises deadlock, second succeeds- def execute_side_effect(query, *args):- if "DELETE FROM" in query:- scan_delete_attempts[0] += 1- if scan_delete_attempts[0] == 1:- # First DELETE attempt raises error- # Create a mock error with pgcode 40P01 for deadlock- error = create_mock_psycopg2_error("deadlock detected", "40P01")- raise error- # Subsequent calls succeed- cursor.rowcount = 50 # Success on retry-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Need to patch time.sleep and run.job_name- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with (- patch("posthog.dags.persons_without_distinct_ids_cleanup.time.sleep"),- patch.object(type(context), "run", PropertyMock(return_value=mock_run)),- ):- scan_delete_chunk_for_pwdc(context, config, chunk)-- # Verify ROLLBACK was called on error- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- # Verify retry succeeded (should have DELETE called twice, COMMIT once)- scan_delete_calls = [call for call in execute_calls if "DELETE FROM" in call]- assert len(scan_delete_calls) >= 1 # At least one successful DELETE-- def test_scan_delete_chunk_error_handling_and_rollback(self):- """Test error handling and rollback on non-duplicate errors."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- mock_db = create_mock_database_resource()- mock_cluster = create_mock_cluster_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- # Raise generic error on INSERT- def execute_side_effect(query, *args):- if "DELETE FROM" in query:- raise Exception("Connection lost")-- cursor.execute.side_effect = execute_side_effect-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pwdc- from unittest.mock import PropertyMock-- mock_run = MagicMock(job_name="test_job")- with patch.object(type(context), "run", PropertyMock(return_value=mock_run)):- # Should raise Dagster.Failure- from dagster import Failure-- try:- scan_delete_chunk_for_pwdc(context, config, chunk)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- # Verify error metadata- assert e.description is not None- assert "Failed to scan and delete rows in batch" in e.description-- # Verify ROLLBACK was called- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- assert "ROLLBACK" in execute_calls-- def test_scan_delete_chunk_query_format(self):- """Test that DELETE query has correct format."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=100,- )- chunk = (1, 100)-- mock_db = create_mock_database_resource(rowcount_values=10)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pwdc- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_pwdc(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Find INSERT query- scan_delete_query = next((call for call in execute_calls if "DELETE FROM" in call), None)- assert scan_delete_query is not None-- # Verify query components- assert f"DELETE FROM {config.persons_table} AS p" in scan_delete_query- assert "WHERE p.id >=" in scan_delete_query- assert "AND p.id <=" in scan_delete_query- assert "NOT EXISTS" in scan_delete_query- assert "ORDER BY p.id DESC" in scan_delete_query-- def test_scan_delete_chunk_session_settings_applied_once(self):- """Test that SET statements are applied once at session level before batch loop."""- config = PersonsNoDistinctIdsCleanupConfig(- chunk_size=1000,- batch_size=50,- )- chunk = (1, 150) # 3 batches-- mock_db = create_mock_database_resource(rowcount_values=25)- mock_cluster = create_mock_cluster_resource()-- context = build_op_context(- resources={"database": mock_db, "cluster": mock_cluster},- )- # Patch context.run.job_name where it's accessed in scan_delete_chunk_for_pwdc- from unittest.mock import PropertyMock-- with patch.object(type(context), "run", PropertyMock(return_value=MagicMock(job_name="test_job"))):- scan_delete_chunk_for_pwdc(context, config, chunk)-- cursor = mock_db.cursor.return_value.__enter__.return_value- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]-- # Count SET statements (should be called once each, before loop)- set_statements = [- "SET application_name",- "SET lock_timeout",- "SET statement_timeout",- "SET maintenance_work_mem",- "SET work_mem",- "SET temp_buffers",- "SET max_parallel_workers_per_gather",- "SET max_parallel_maintenance_workers",- "SET synchronous_commit",- ]-- for stmt in set_statements:- count = sum(1 for call in execute_calls if stmt in call)- assert count == 1, f"Expected {stmt} to be called once, but it was called {count} times"-- # Verify SET statements come before BEGIN statements- set_indices = [i for i, call in enumerate(execute_calls) if any(stmt in call for stmt in set_statements)]- begin_indices = [i for i, call in enumerate(execute_calls) if call == "BEGIN"]-- if set_indices and begin_indices:- assert max(set_indices) < min(begin_indices), "SET statements should come before BEGIN statements"---class TestGetIdRangeForPwdc:- """Test the get_id_range_for_pwdc function."""-- def test_get_id_range_uses_min_id_override(self):- """Test that min_id override is honored when provided."""- config = PersonsNoDistinctIdsCleanupConfig(min_id=100, max_id=None)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"max_id": 5000}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pwdc(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used-- # Verify min_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"-- # Verify max_id query WAS executed- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(max_queries) == 1, "Should query for max_id when override is not provided"-- def test_get_id_range_uses_max_id_override(self):- """Test that max_id override is honored when provided."""- config = PersonsNoDistinctIdsCleanupConfig(min_id=None, max_id=5000)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- cursor.fetchone.return_value = {"min_id": 1}-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pwdc(context, config)-- assert result == (1, 5000)- assert result[1] == 5000 # max_id override used-- # Verify max_id query was NOT executed (override used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- # Verify min_id query WAS executed- min_queries = [call for call in execute_calls if "MIN(id)" in call]- assert len(min_queries) == 1, "Should query for min_id when override is not provided"-- def test_get_id_range_uses_both_overrides(self):- """Test that both min_id and max_id overrides are honored when provided."""- config = PersonsNoDistinctIdsCleanupConfig(min_id=100, max_id=5000)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pwdc(context, config)-- assert result == (100, 5000)- assert result[0] == 100 # min_id override used- assert result[1] == 5000 # max_id override used-- # Verify NO queries were executed (both overrides used)- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(min_queries) == 0, "Should not query for min_id when override is provided"- assert len(max_queries) == 0, "Should not query for max_id when override is provided"-- def test_get_id_range_queries_database_when_no_overrides(self):- """Test that database is queried when no overrides are provided."""- config = PersonsNoDistinctIdsCleanupConfig(min_id=None, max_id=None)- mock_db = create_mock_database_resource()-- cursor = mock_db.cursor.return_value.__enter__.return_value- # First call returns min_id, second call returns max_id- cursor.fetchone.side_effect = [{"min_id": 1}, {"max_id": 5000}]-- context = build_op_context(resources={"database": mock_db})-- result = get_id_range_for_pwdc(context, config)-- assert result == (1, 5000)-- # Verify both queries were executed- execute_calls = [call[0][0] for call in cursor.execute.call_args_list]- min_queries = [call for call in execute_calls if "MIN(id)" in call]- max_queries = [call for call in execute_calls if "MAX(id)" in call]- assert len(min_queries) == 1, "Should query for min_id when override is not provided"- assert len(max_queries) == 1, "Should query for max_id when override is not provided"-- def test_get_id_range_validates_max_id_greater_than_min_id(self):- """Test that validation fails when max_id < min_id."""- config = PersonsNoDistinctIdsCleanupConfig(min_id=5000, max_id=100)- mock_db = create_mock_database_resource()-- context = build_op_context(resources={"database": mock_db})-- from dagster import Failure-- try:- get_id_range_for_pwdc(context, config)- raise AssertionError("Expected Dagster.Failure to be raised")- except Failure as e:- assert e.description is not None- description = e.description- assert "max_id" in description.lower() or "invalid" in description.lower()- assert "5000" in description or "100" in description