Skip to content

: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.

chore(django): remove unneeded management commands (#65839)

Zach Brown382791680580
diff --git a/posthog/management/commands/delete_persons.py b/posthog/management/commands/delete_persons.py
deleted file mode 100644
index 89cf15693fab..000000000000
--- a/posthog/management/commands/delete_persons.py
+++ /dev/null
@@ -1,230 +0,0 @@
-from collections.abc import Callable
-from dataclasses import asdict, dataclass
-
-from django.core.management.base import BaseCommand
-from django.db import connection, connections
-
-from psycopg import sql
-
-from posthog.models.person import Person
-
-
-@dataclass(frozen=True)
-class DeleteOptions:
- team_id: int
- person_ids: list[int]
- batch_size: int
- batches: int
- live_run: bool
- write: Callable[[str], None]
-
- @property
- def for_specific_persons(self) -> bool:
- return len(self.person_ids) > 0
-
-
-@dataclass(frozen=True)
-class DeleteBatchResult:
- distinct_ids_deleted: int
- person_overrides_deleted: int
- cohort_people_deleted: int
- persons_deleted: int
-
-
-@dataclass(frozen=True)
-class DeleteQueries:
- person_distinct_ids: sql.Composed
- person_override: sql.Composed
- cohort_people: sql.Composed
- person: sql.Composed
-
-
-def build_delete_queries(*, for_specific_persons: bool) -> DeleteQueries:
- """
- Build SQL queries for deleting persons and related records.
-
- Uses sql.Identifier to safely escape table names (protection against SQL injection).
- Uses parameterized queries for all values.
- """
- person_table = sql.Identifier(Person._meta.db_table)
-
- if for_specific_persons:
- select_query = sql.SQL("""
- SELECT id
- FROM {person_table}
- WHERE team_id=%(team_id)s AND id = ANY(%(person_ids)s::integer[])
- ORDER BY id ASC
- LIMIT %(limit)s
- """).format(person_table=person_table)
- else:
- select_query = sql.SQL("""
- SELECT id
- FROM {person_table}
- WHERE team_id=%(team_id)s
- ORDER BY id ASC
- LIMIT %(limit)s
- """).format(person_table=person_table)
-
- return DeleteQueries(
- person_distinct_ids=sql.SQL("""
- WITH to_delete AS ({select_query})
- DELETE FROM posthog_persondistinctid
- WHERE person_id IN (SELECT id FROM to_delete);
- """).format(select_query=select_query),
- person_override=sql.SQL("""
- WITH to_delete AS ({select_query})
- DELETE FROM posthog_personoverride
- WHERE (old_person_id IN (SELECT id FROM to_delete) OR override_person_id IN (SELECT id FROM to_delete));
- """).format(select_query=select_query),
- cohort_people=sql.SQL("""
- WITH to_delete AS ({select_query})
- DELETE FROM posthog_cohortpeople
- WHERE person_id IN (SELECT id FROM to_delete);
- """).format(select_query=select_query),
- person=sql.SQL("""
- WITH to_delete AS ({select_query})
- DELETE FROM {person_table}
- WHERE id IN (SELECT id FROM to_delete);
- """).format(select_query=select_query, person_table=person_table),
- )
-
-
-def delete_persons_batch(team_id: int, person_ids: list[int], batch_size: int) -> DeleteBatchResult:
- """
- Delete a batch of persons and their related records from postgres.
-
- Args:
- team_id: The team to delete persons from
- person_ids: List of specific person IDs to delete. Empty list means all persons for the team.
- batch_size: Maximum number of persons to delete in this batch
-
- Returns:
- Counts of deleted records for each table
- """
- for_specific_persons = len(person_ids) > 0
- queries = build_delete_queries(for_specific_persons=for_specific_persons)
- params: dict[str, int | list[int]] = {"team_id": team_id, "limit": batch_size, "person_ids": person_ids}
-
- conn = connections["persons_db_writer"] if "persons_db_writer" in connections else connection
- with conn.cursor() as cursor:
- cursor.execute(queries.person_distinct_ids, params)
- distinct_ids_deleted = cursor.rowcount
-
- cursor.execute(queries.person_override, params)
- person_overrides_deleted = cursor.rowcount
-
- cursor.execute(queries.cohort_people, params)
- cohort_people_deleted = cursor.rowcount
-
- cursor.execute(queries.person, params)
- persons_deleted = cursor.rowcount
-
- return DeleteBatchResult(
- distinct_ids_deleted=distinct_ids_deleted,
- person_overrides_deleted=person_overrides_deleted,
- cohort_people_deleted=cohort_people_deleted,
- persons_deleted=persons_deleted,
- )
-
-
-class Command(BaseCommand):
- help = "Delete a batch of persons from postgres"
-
- def add_arguments(self, parser):
- parser.add_argument("--team-id", default=None, type=int, help="Specify a team to delete persons from.")
- parser.add_argument(
- "--person-ids", default=None, type=str, help="Specify a list of comma separated person ids to be deleted."
- )
- parser.add_argument(
- "--delete-all-persons-for-team",
- action="store_true",
- help="Delete ALL persons for the team. Required if --person-ids is not provided.",
- )
- parser.add_argument("--batch-size", default=1000, type=int, help="Number of rows to be deleted per batch")
- parser.add_argument("--batches", default=1, type=int, help="Number of batches to run")
- parser.add_argument("--live-run", action="store_true", help="Run changes, default is dry-run")
-
- def handle(self, *args, **options):
- team_id = options["team_id"]
- if not team_id:
- self.stderr.write("ERROR: You must specify --team-id to run this script")
- return exit(1)
-
- person_ids_raw = options["person_ids"]
- person_ids = [int(pid.strip()) for pid in person_ids_raw.split(",") if pid.strip()] if person_ids_raw else []
- delete_all = options["delete_all_persons_for_team"]
-
- if person_ids_raw and not person_ids:
- self.stderr.write("ERROR: --person-ids was provided but contained no valid IDs")
- return exit(1)
-
- if not person_ids and not delete_all:
- self.stderr.write("ERROR: You must specify --person-ids or --delete-all-persons-for-team")
- return exit(1)
-
- if person_ids and delete_all:
- self.stderr.write("ERROR: Cannot specify both --person-ids and --delete-all-persons-for-team")
- return exit(1)
-
- opts = DeleteOptions(
- team_id=team_id,
- person_ids=person_ids,
- batch_size=options["batch_size"],
- batches=options["batches"],
- live_run=options["live_run"],
- write=self.stdout.write,
- )
- run(opts)
-
-
-def run(opts: DeleteOptions):
- write = opts.write
-
- write("Plan:")
- write(f"-> Team ID: {opts.team_id}")
- if opts.person_ids:
- write(f"-> Person IDs: {opts.person_ids}")
- else:
- write("-> Deleting ALL persons for team")
- write(f"-> Batches: {opts.batches} of {opts.batch_size}")
-
- queries = build_delete_queries(for_specific_persons=opts.for_specific_persons)
- params: dict[str, int | list[int]] = {
- "team_id": opts.team_id,
- "limit": opts.batch_size,
- "person_ids": opts.person_ids,
- }
-
- conn = connections["persons_db_writer"] if "persons_db_writer" in connections else connection
- with conn.cursor() as cursor:
- prepared_queries = {name: cursor.mogrify(query, params) for name, query in asdict(queries).items()}
-
- write("Delete queries to run:")
- for name, prepared_query in prepared_queries.items():
- write(f"{name}: {prepared_query}")
-
- if not opts.live_run:
- write("Dry run. Set --live-run to actually delete.")
- return exit(0)
-
- confirm = input("Type 'delete' to confirm: ")
-
- if confirm != "delete":
- write("Aborting")
- return exit(0)
-
- write("Executing delete queries...")
-
- for i in range(opts.batches):
- write(f"Deleting batch {i + 1} of {opts.batches} ({opts.batch_size} rows)")
- result = delete_persons_batch(opts.team_id, opts.person_ids, opts.batch_size)
- write(f"Deleted {result.distinct_ids_deleted} distinct_ids")
- write(f"Deleted {result.person_overrides_deleted} person overrides")
- write(f"Deleted {result.cohort_people_deleted} cohort people")
- write(f"Deleted {result.persons_deleted} persons")
-
- if result.persons_deleted < opts.batch_size:
- write(f"Exiting early as we received less than {opts.batch_size} rows")
- break
-
- write("Done")
diff --git a/posthog/management/commands/fix_cohort_people_unsynced_ch.py b/posthog/management/commands/fix_cohort_people_unsynced_ch.py
deleted file mode 100644
index f6d4a2e13281..000000000000
--- a/posthog/management/commands/fix_cohort_people_unsynced_ch.py
+++ /dev/null
@@ -1,246 +0,0 @@
-from django.core.management.base import BaseCommand
-from django.db import connections
-
-import structlog
-
-from posthog.clickhouse.client import sync_execute
-from posthog.models.person import Person
-from posthog.person_db_router import PERSONS_DB_FOR_READ
-
-from products.cohorts.backend.models.cohort import Cohort
-
-logger = structlog.get_logger(__name__)
-
-# Use centralized database routing constant
-READ_DB_FOR_PERSONS = PERSONS_DB_FOR_READ
-
-BATCH_SIZE = 10000
-PROD_US_CUTOFF = "2025-10-01 00:00:00"
-
-
-class Command(BaseCommand):
- help = (
- "Sync cohort people records from ClickHouse person_static_cohort table to PostgreSQL posthog_cohortpeople table"
- )
-
- def add_arguments(self, parser):
- parser.add_argument(
- "--batch-size", type=int, default=BATCH_SIZE, help="Number of records to process in each batch"
- )
- parser.add_argument("--dry-run", action="store_true", help="Show what would be done without making changes")
- parser.add_argument(
- "--start-date",
- type=str,
- default=PROD_US_CUTOFF,
- help="Start date for records to sync (format: 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DD')",
- )
-
- def handle(self, *args, **options):
- batch_size = options["batch_size"]
- dry_run = options["dry_run"]
- start_date = options["start_date"]
-
- if dry_run:
- self.stdout.write(self.style.WARNING("Running in dry-run mode - no changes will be made"))
-
- self.stdout.write(f"Configuration: batch_size={batch_size}, start_date={start_date}")
-
- # Use persons database for reading person data
- persons_db = READ_DB_FOR_PERSONS
-
- self.stdout.write(f"Using database connection: {persons_db}")
- self.stdout.write(f"Starting cohort people sync for records after {start_date}")
-
- try:
- # Process ClickHouse data in batches and handle each batch completely
- total_inserted = 0
- cohorts_with_insertions = set()
- last_timestamp = start_date
- last_person_id = None
- last_cohort_id = 0
- first_batch = True
-
- while True:
- # Use keyset pagination for better performance
- if first_batch:
- batch_query = """
- SELECT DISTINCT person_id, cohort_id, team_id, _timestamp
- FROM person_static_cohort
- WHERE _timestamp >= %(cutoff_timestamp)s
- ORDER BY _timestamp, person_id, cohort_id
- LIMIT %(batch_size)s
- """
- params = {
- "cutoff_timestamp": start_date,
- "batch_size": batch_size,
- }
- else:
- batch_query = """
- SELECT DISTINCT person_id, cohort_id, team_id, _timestamp
- FROM person_static_cohort
- WHERE (_timestamp > %(last_timestamp)s)
- OR (_timestamp = %(last_timestamp)s AND person_id > %(last_person_id)s)
- OR (_timestamp = %(last_timestamp)s AND person_id = %(last_person_id)s AND cohort_id > %(last_cohort_id)s)
- ORDER BY _timestamp, person_id, cohort_id
- LIMIT %(batch_size)s
- """
- params = {
- "last_timestamp": last_timestamp,
- "last_person_id": last_person_id,
- "last_cohort_id": last_cohort_id,
- "batch_size": batch_size,
- }
-
- clickhouse_batch = sync_execute(batch_query, params)
- first_batch = False
-
- if not clickhouse_batch:
- break
-
- self.stdout.write(
- self.style.SUCCESS(
- f"Processing ClickHouse batch: {len(clickhouse_batch)} records (last: {last_timestamp})"
- )
- )
-
- # Extract unique person UUIDs from this batch
- ch_person_uuids = list({str(record[0]) for record in clickhouse_batch})
-
- if not ch_person_uuids:
- # Update keyset pagination cursor even if no UUIDs found
- last_record = clickhouse_batch[-1]
- last_timestamp = last_record[3]
- last_person_id = str(last_record[0])
- last_cohort_id = last_record[1]
- continue
-
- # Use the correct database connection
- person_connection = connections[persons_db]
-
- # Get person ID mappings from persons database for this batch
- person_uuid_to_id = {}
- person_table = Person._meta.db_table
- with person_connection.cursor() as cursor:
- cursor.execute(f"SELECT uuid, id FROM {person_table} WHERE uuid = ANY(%s)", [ch_person_uuids])
- for uuid, person_id in cursor.fetchall():
- person_uuid_to_id[str(uuid)] = person_id
-
- if not person_uuid_to_id:
- self.stdout.write(f"No matching persons found for batch")
- # Update keyset pagination cursor
- last_record = clickhouse_batch[-1]
- last_timestamp = last_record[3]
- last_person_id = str(last_record[0])
- last_cohort_id = last_record[1]
- continue
-
- self.stdout.write(f"Found {len(person_uuid_to_id)} person ID mappings for batch")
-
- # Build the cohort data mapping from this ClickHouse batch
- cohort_data: dict[str, set[int]] = {}
- for record in clickhouse_batch:
- record_person_uuid = str(record[0])
- cohort_id = record[1]
- if record_person_uuid not in cohort_data:
- cohort_data[record_person_uuid] = set()
- cohort_data[record_person_uuid].add(cohort_id)
-
- insert_values = []
- for person_uuid, cohort_ids in cohort_data.items():
- if person_uuid not in person_uuid_to_id:
- continue
- person_id = person_uuid_to_id[person_uuid]
- for cohort_id in cohort_ids:
- insert_values.append((cohort_id, person_id))
-
- if insert_values:
- if dry_run:
- self.stdout.write(f"DRY RUN: Would insert {len(insert_values)} records")
- # Show sample of what would be inserted
- sample_size = min(5, len(insert_values))
- for cohort_id, person_id in insert_values[:sample_size]:
- self.stdout.write(f" Would insert: cohort_id={cohort_id}, person_id={person_id}")
- if sample_size < len(insert_values):
- self.stdout.write(f" ... and {len(insert_values) - sample_size} more records")
-
- # Track cohorts that would have insertions in dry run
- cohorts_in_batch = {cohort_id for cohort_id, _ in insert_values}
- cohorts_with_insertions.update(cohorts_in_batch)
- else:
- # Group by cohort_id and collect person UUIDs
- person_id_to_uuid = {pid: uuid for uuid, pid in person_uuid_to_id.items()}
- cohort_to_uuids: dict[int, list[str]] = {}
- for cohort_id, person_id in insert_values:
- uuid = person_id_to_uuid.get(person_id)
-
- if uuid is not None:
- if cohort_id not in cohort_to_uuids:
- cohort_to_uuids[cohort_id] = []
- cohort_to_uuids[cohort_id].append(uuid)
-
- batch_inserted = 0
-
- for cohort_id, person_uuids in cohort_to_uuids.items():
- try:
- cohort = Cohort.objects.get(id=cohort_id)
- cohort.insert_users_list_by_uuid_into_pg_only(
- items=person_uuids, team_id=cohort.team_id
- )
- batch_inserted += len(person_uuids)
- except Exception as e:
- self.stdout.write(self.style.ERROR(f"Error inserting into cohort {cohort_id}: {e}"))
-
- total_inserted += batch_inserted
-
- # Only track cohorts that actually had records inserted
- if batch_inserted > 0:
- cohorts_in_batch = set(cohort_to_uuids.keys())
- cohorts_with_insertions.update(cohorts_in_batch)
-
- self.stdout.write(self.style.SUCCESS(f"Batch successful: {batch_inserted} records inserted"))
- else:
- self.stdout.write(f"No new records to insert for batch")
-
- # Update keyset pagination cursor to last record in batch
- last_record = clickhouse_batch[-1]
- last_timestamp = last_record[3]
- last_person_id = str(last_record[0])
- last_cohort_id = last_record[1]
-
- if dry_run:
- self.stdout.write(
- self.style.SUCCESS(
- f"DRY RUN COMPLETE: Would have inserted records into {len(cohorts_with_insertions)} cohorts"
- )
- )
- else:
- self.stdout.write(
- self.style.SUCCESS(f"Cohort people sync completed: {total_inserted} records inserted")
- )
-
- # Trigger cohort recalculation only for cohorts that had new people inserted
- if cohorts_with_insertions:
- self.stdout.write(
- f"Triggering recalculation for {len(cohorts_with_insertions)} cohorts: {list(cohorts_with_insertions)}"
- )
- try:
- from posthog.tasks.calculate_cohort import increment_version_and_enqueue_calculate_cohort
-
- for cohort in Cohort.objects.filter(id__in=cohorts_with_insertions).iterator():
- try:
- increment_version_and_enqueue_calculate_cohort(cohort, initiating_user=None)
- self.stdout.write(f"Triggered recalculation for cohort {cohort.id}")
- except Exception as e:
- self.stdout.write(
- self.style.ERROR(f"Failed to trigger recalculation for cohort {cohort.id}: {e}")
- )
-
- self.stdout.write(self.style.SUCCESS("Completed cohort recalculation triggers"))
- except ImportError as e:
- self.stdout.write(self.style.ERROR(f"Could not import cohort calculation functions: {e}"))
- except Exception as e:
- self.stdout.write(self.style.ERROR(f"Failed to trigger cohort recalculations: {e}"))
-
- except Exception as e:
- self.stdout.write(self.style.ERROR(f"Error syncing cohort people: {e}"))
- raise
diff --git a/posthog/management/commands/split_person.py b/posthog/management/commands/split_person.py
deleted file mode 100644
index 26f070f21a4c..000000000000
--- a/posthog/management/commands/split_person.py
+++ /dev/null
@@ -1,77 +0,0 @@
-import logging
-
-from django.core.management.base import BaseCommand
-
-import structlog
-
-from posthog.kafka_client.routing import flush_all_producers
-from posthog.models import Person
-
-logger = structlog.get_logger(__name__)
-logger.setLevel(logging.INFO)
-
-
-class Command(BaseCommand):
- help = (
- "Split a person into one new person per distinct_id, to recover from bad merges. "
- "Useful when the API endpoint timeouts."
- )
-
- def add_arguments(self, parser):
- parser.add_argument("--team-id", default=None, type=int, help="Specify a team to fix data for.")
- parser.add_argument(
- "--person-id",
- default=None,
- type=int,
- help="Specify the person ID to split.",
- )
- parser.add_argument("--live-run", action="store_true", help="Run changes, default is dry-run")
- parser.add_argument(
- "--max-splits",
- default=None,
- type=int,
- help="Only split off a given number of distinct_ids and exit.",
- )
-
- def handle(self, *args, **options):
- run(options)
-
-
-def run(options):
- live_run = options["live_run"]
-
- if options["team_id"] is None:
- logger.error("You must specify --team-id to run this script")
- exit(1)
-
- if options["person_id"] is None:
- logger.error("You must specify --person-id to run this script")
- exit(1)
-
- team_id = options["team_id"]
- person_id = options["person_id"]
- max_splits = options["max_splits"]
-
- person = Person.objects.get(team_id=team_id, pk=person_id) # nosemgrep: no-direct-persons-db-orm
- if person.team_id != team_id:
- logger.error(f"Specified person belongs to different team {person.team_id}")
- exit(1)
-
- distinct_id_count = len(person.distinct_ids)
- if distinct_id_count < 2:
- logger.error(f"Specified person only has {distinct_id_count} IDs, cannot split")
- exit(1)
-
- if max_splits:
- will_split = min(max_splits, distinct_id_count)
- logger.info(f"Splitting {will_split} of the {distinct_id_count} distinct_ids")
- else:
- logger.info(f"Splitting all of the {distinct_id_count} distinct_ids")
-
- if live_run:
- person.split_person(None, max_splits)
- logger.info("Waiting on Kafka producer flush, for up to 5 minutes")
- flush_all_producers(5 * 60)
- logger.info("Kafka producer queue flushed.")
- else:
- logger.info("Skipping the split, pass --live-run to run it")
diff --git a/posthog/models/test/test_delete_persons_query.py b/posthog/models/test/test_delete_persons_query.py
deleted file mode 100644
index 7dccfe23f076..000000000000
--- a/posthog/models/test/test_delete_persons_query.py
+++ /dev/null
@@ -1,86 +0,0 @@
-from posthog.test.base import BaseTest
-
-from posthog.management.commands.delete_persons import delete_persons_batch
-from posthog.models import Person, Team
-
-
-class TestDeletePersonsBatch(BaseTest):
- """
- Tests that verify the delete_persons_batch function deletes the correct persons.
- """
-
- def setUp(self):
- super().setUp()
- self.person1 = Person.objects.create(team=self.team, properties={"name": "person1"})
- self.person2 = Person.objects.create(team=self.team, properties={"name": "person2"})
- self.person3 = Person.objects.create(team=self.team, properties={"name": "person3"})
-
- self.other_team = Team.objects.create(organization=self.organization, name="Other Team")
- self.other_person = Person.objects.create(team=self.other_team, properties={"name": "other"})
-
- def get_remaining_person_ids(self) -> set[int]:
- return set(Person.objects.filter(team=self.team).values_list("id", flat=True))
-
- def test_deletes_all_persons_for_team_when_no_filter(self):
- """When person_ids is empty list, delete ALL persons for the team."""
- result = delete_persons_batch(team_id=self.team.id, person_ids=[], batch_size=1000)
-
- assert result.persons_deleted == 3
- assert self.get_remaining_person_ids() == set()
- assert Person.objects.filter(id=self.other_person.id).exists()
-
- def test_deletes_only_specified_persons_when_filtered(self):
- """When person_ids is provided, delete only those persons."""
- result = delete_persons_batch(
- team_id=self.team.id,
- person_ids=[self.person1.id, self.person3.id],
- batch_size=1000,
- )
-
- assert result.persons_deleted == 2
- assert self.get_remaining_person_ids() == {self.person2.id}
-
- def test_deletes_single_person(self):
- """When a single person_id is provided, delete only that person."""
- result = delete_persons_batch(
- team_id=self.team.id,
- person_ids=[self.person2.id],
- batch_size=1000,
- )
-
- assert result.persons_deleted == 1
- assert self.get_remaining_person_ids() == {self.person1.id, self.person3.id}
-
- def test_deletes_nothing_when_person_ids_dont_exist(self):
- """When person_ids don't exist in team, delete nothing."""
- result = delete_persons_batch(
- team_id=self.team.id,
- person_ids=[999999, 999998],
- batch_size=1000,
- )
-
- assert result.persons_deleted == 0
- assert self.get_remaining_person_ids() == {self.person1.id, self.person2.id, self.person3.id}
-
- def test_deletes_nothing_when_person_ids_belong_to_other_team(self):
- """When person_ids belong to another team, delete nothing."""
- result = delete_persons_batch(
- team_id=self.team.id,
- person_ids=[self.other_person.id],
- batch_size=1000,
- )
-
- assert result.persons_deleted == 0
- assert self.get_remaining_person_ids() == {self.person1.id, self.person2.id, self.person3.id}
- assert Person.objects.filter(id=self.other_person.id).exists()
-
- def test_respects_batch_size_limit(self):
- """Batch size limits how many persons are deleted in one call."""
- result = delete_persons_batch(
- team_id=self.team.id,
- person_ids=[],
- batch_size=2,
- )
-
- assert result.persons_deleted == 2
- assert len(self.get_remaining_person_ids()) == 1