: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: remove one-shot backfill management commands (#68836)
Frank Hamandfd766c60057f
diff --git a/posthog/management/commands/add_question_ids_to_surveys.py b/posthog/management/commands/add_question_ids_to_surveys.pydeleted file mode 100644index 7e2c3fb4c72d..000000000000--- a/posthog/management/commands/add_question_ids_to_surveys.py+++ /dev/null@@ -1,165 +0,0 @@-import uuid-import logging--from django.core.management.base import BaseCommand-from django.db import transaction--from products.surveys.backend.models import Survey--logger = logging.getLogger(__name__)---class Command(BaseCommand):- help = "Add unique IDs to each question in existing surveys that don't have them"-- def add_arguments(self, parser):- parser.add_argument(- "--batch-size",- type=int,- default=1000,- help="Number of surveys to process in each batch (default: 1000)",- )- parser.add_argument(- "--really-run",- action="store_true",- help="Actually make changes to the database. Without this flag, runs in dry-run mode.",- )- parser.add_argument(- "--verbose",- action="store_true",- help="Show detailed information about the process",- )-- def handle(self, *args, **options):- batch_size = options["batch_size"]- really_run = options["really_run"]- verbose = options["verbose"]-- if not really_run:- self.stdout.write(self.style.WARNING("Running in dry-run mode - no changes will be made"))- self.stdout.write(self.style.WARNING("Use --really-run to actually make changes"))-- self.stdout.write(- self.style.WARNING(- "Note: This command may not be necessary for new surveys as IDs are automatically added via pre_save signal"- )- )- self.stdout.write(- self.style.WARNING(- "It's primarily useful for older surveys created before the pre_save signal was implemented"- )- )-- self.add_question_ids_to_surveys(batch_size=batch_size, really_run=really_run, verbose=verbose)-- def add_question_ids_to_surveys(self, batch_size: int, really_run: bool, verbose: bool) -> None:- """- Add unique IDs to each question in existing surveys.- This ensures all questions have an ID for tracking responses.-- Processes surveys in small batches to minimize memory usage.- Uses proper row locking to prevent race conditions.- """- total_surveys = Survey.objects.filter(questions__isnull=False).count()- total_modified = 0- total_questions_updated = 0- total_processed = 0-- self.stdout.write(f"Found {total_surveys} surveys to process")-- # Process in batches to minimize memory usage- offset = 0-- while True:- # Process one batch at a time- with transaction.atomic():- # Get a batch of surveys WITH ROW LOCKING- # This ensures no one else can modify these rows while we're processing them- surveys = list(- Survey.objects.filter(questions__isnull=False)- .order_by("pk")- .select_for_update(skip_locked=True) # Add row locking- .only("id", "questions")[- # Only fetch fields we need- offset : offset + batch_size- ]- )-- if not surveys:- # If we got no surveys, we're done- break-- batch_modified = 0- batch_questions_updated = 0- surveys_to_update = []-- for survey in surveys:- # Skip surveys with empty questions list- if not survey.questions:- continue-- # Add IDs to questions that don't have them- modified = False- questions_updated = 0-- for question in survey.questions:- if not question.get("id"):- question["id"] = str(uuid.uuid4())- modified = True- questions_updated += 1-- # Add survey to update list if any questions were modified- if modified:- batch_modified += 1- batch_questions_updated += questions_updated- surveys_to_update.append(survey)-- if verbose:- self.stdout.write(f"Survey {survey.id}: Added IDs to {questions_updated} questions")-- # Update all modified surveys in this batch- if surveys_to_update and really_run:- Survey.objects.bulk_update(surveys_to_update, ["questions"])-- total_modified += batch_modified- total_questions_updated += batch_questions_updated- total_processed += len(surveys)-- # Report progress- processed_so_far = offset + len(surveys)- percent_complete = (processed_so_far / total_surveys) * 100 if total_surveys > 0 else 100-- self.stdout.write(- f"Processed batch of {len(surveys)} surveys: "- f"Modified {batch_modified} surveys, "- f"Updated {batch_questions_updated} questions. "- f"Progress: {processed_so_far}/{total_surveys} ({percent_complete:.1f}%)"- )-- # Move to the next batch- offset += len(surveys) # Use actual number of surveys processed, not batch_size-- # Check if we processed all surveys- if total_processed < total_surveys:- self.stdout.write(- self.style.WARNING(- f"Note: Only processed {total_processed} out of {total_surveys} surveys. "- f"The remaining {total_surveys - total_processed} surveys may have been locked "- f"by other processes. These surveys will likely get question IDs automatically "- f"via the pre_save signal when they are next updated."- )- )-- if not really_run:- self.stdout.write(- self.style.SUCCESS(- f"DRY RUN COMPLETE: Would have modified {total_modified} surveys "- f"and updated {total_questions_updated} questions"- )- )- else:- self.stdout.write(- self.style.SUCCESS(- f"Successfully modified {total_modified} surveys and updated {total_questions_updated} questions"- )- )diff --git a/posthog/management/commands/backfill_user_joined_notification_settings.py b/posthog/management/commands/backfill_user_joined_notification_settings.pydeleted file mode 100644index c451c8e37efe..000000000000--- a/posthog/management/commands/backfill_user_joined_notification_settings.py+++ /dev/null@@ -1,100 +0,0 @@-from typing import Any--from django.core.management.base import BaseCommand-from django.db import connection, transaction--ORG_MEMBER_JOIN_KEY = "organization_member_join_email_disabled"-BATCH_SIZE = 5000--COUNT_SQL = f"""-SELECT COUNT(*) FROM (- SELECT m.user_id- FROM posthog_organizationmembership m- JOIN posthog_organization o ON o.id = m.organization_id- JOIN posthog_user u ON u.id = m.user_id- WHERE NOT COALESCE(u.partial_notification_settings, '{{}}')::jsonb ? '{ORG_MEMBER_JOIN_KEY}'- GROUP BY m.user_id-) t-"""--UPDATE_BATCH_SQL = f"""-WITH eligible AS (- SELECT u.id- FROM posthog_user u- WHERE EXISTS (- SELECT 1 FROM posthog_organizationmembership m WHERE m.user_id = u.id- )- AND NOT COALESCE(u.partial_notification_settings, '{{}}')::jsonb ? '{ORG_MEMBER_JOIN_KEY}'- ORDER BY u.id- LIMIT {BATCH_SIZE}-),-org_map AS (- SELECT- m.user_id,- jsonb_object_agg(- m.organization_id::text,- NOT COALESCE(o.is_member_join_email_enabled, true)- ) AS from_orgs- FROM posthog_organizationmembership m- JOIN posthog_organization o ON o.id = m.organization_id- INNER JOIN eligible e ON e.id = m.user_id- GROUP BY m.user_id-)-UPDATE posthog_user u-SET partial_notification_settings = (- COALESCE(u.partial_notification_settings::jsonb, '{{}}'::jsonb)- || jsonb_build_object(- '{ORG_MEMBER_JOIN_KEY}',- org_map.from_orgs- )-)-FROM org_map-WHERE u.id = org_map.user_id-"""---class Command(BaseCommand):- help = (- "Backfill user partial_notification_settings.organization_member_join_email_disabled from each "- "organization's is_member_join_email_enabled for organizations the user belongs to."- )-- def add_arguments(self, parser):- parser.add_argument(- "--dry-run",- action="store_true",- help="Show how many users would be updated without writing changes.",- )-- def handle(self, *args: Any, **options: Any) -> None:- dry_run: bool = options["dry_run"]-- with connection.cursor() as cursor:- cursor.execute(COUNT_SQL)- row = cursor.fetchone()- assert row is not None- (would_update,) = row-- self.stdout.write(- f"Users with at least one organization membership and no '{ORG_MEMBER_JOIN_KEY}' "- f"setting yet: {would_update}"- )-- if dry_run:- self.stdout.write(self.style.WARNING("Dry run — no changes written."))- return-- total_updated = 0- batch_index = 0- while True:- with transaction.atomic():- with connection.cursor() as cursor:- cursor.execute(UPDATE_BATCH_SQL)- updated = cursor.rowcount- if updated == 0:- break- total_updated += updated- batch_index += 1- self.stdout.write(f"Batch {batch_index}: updated {updated} user(s) (running total: {total_updated}).")-- self.stdout.write(self.style.SUCCESS(f"Done. Updated {total_updated} user(s) in {batch_index} batch(es)."))diff --git a/posthog/management/commands/extend_cookieless_ttls.py b/posthog/management/commands/extend_cookieless_ttls.pydeleted file mode 100644index 15f0c86e83a5..000000000000--- a/posthog/management/commands/extend_cookieless_ttls.py+++ /dev/null@@ -1,152 +0,0 @@-import os--from django.core.management.base import BaseCommand--import structlog--from posthog.redis import get_client--logger = structlog.get_logger(__name__)---def get_cookieless_redis_client():- """Get Redis client for cookieless instance."""- cookieless_host = os.getenv("COOKIELESS_REDIS_HOST", "")-- if not cookieless_host:- raise ValueError(- "COOKIELESS_REDIS_HOST environment variable is not set. "- "This command requires explicit cookieless Redis configuration."- )-- cookieless_port = os.getenv("COOKIELESS_REDIS_PORT", "6379")- redis_url = f"redis://{cookieless_host}:{cookieless_port}/"- logger.info(f"Connecting to cookieless Redis: {cookieless_host}:{cookieless_port}")- return get_client(redis_url)---class Command(BaseCommand):- help = "Extend TTL for cookieless Redis keys when upgrading from 24h to 72h ingestion lag support"-- def add_arguments(self, parser):- parser.add_argument(- "--dry-run",- action="store_true",- help="Preview changes without modifying Redis keys",- )- parser.add_argument(- "--batch-size",- type=int,- default=1000,- help="Number of keys to process per batch (default: 1000)",- )-- def handle(self, *args, **options):- dry_run = options["dry_run"]- batch_size = options["batch_size"]-- # Show which Redis instance we're connecting to- cookieless_host = os.getenv("COOKIELESS_REDIS_HOST", "")- cookieless_port = os.getenv("COOKIELESS_REDIS_PORT", "6379")- self.stdout.write(self.style.SUCCESS(f"Connecting to cookieless Redis: {cookieless_host}:{cookieless_port}"))-- if dry_run:- self.stdout.write(self.style.WARNING("DRY RUN MODE - No changes will be made"))-- redis_client = get_cookieless_redis_client()-- # Define key patterns and their TTL extensions- key_configs = [- {- "pattern": "cookieless_salt:*",- "extension_seconds": 172800, # +48 hours (24h → 72h)- "description": "Salt keys",- },- {- "pattern": "cklss:*",- "extension_seconds": 172800, # +48 hours (24h → 72h)- "description": "Session keys",- },- {- "pattern": "cklsi:*",- "extension_seconds": 180000, # +50 hours (70h → 120h)- "description": "Identifies keys",- },- ]-- total_processed = 0- total_extended = 0- total_skipped = 0-- for config in key_configs:- pattern = config["pattern"]- extension_seconds = config["extension_seconds"]- description = config["description"]-- self.stdout.write(f"\nProcessing {description} (pattern: {pattern})...")-- processed, extended, skipped = self._process_pattern(- redis_client, pattern, extension_seconds, batch_size, dry_run- )-- total_processed += processed- total_extended += extended- total_skipped += skipped-- self.stdout.write(- self.style.SUCCESS(f" {description}: {processed} processed, {extended} extended, {skipped} skipped")- )-- # Summary- self.stdout.write("\n" + "=" * 60)- self.stdout.write(self.style.SUCCESS(f"SUMMARY:"))- self.stdout.write(f" Total keys processed: {total_processed}")- self.stdout.write(f" Total keys extended: {total_extended}")- self.stdout.write(f" Total keys skipped: {total_skipped}")- if dry_run:- self.stdout.write(self.style.WARNING("\nDRY RUN - No changes were made"))- self.stdout.write("=" * 60)-- def _process_pattern(self, redis_client, pattern, extension_seconds, batch_size, dry_run):- """Scan and extend TTL for keys matching the pattern"""- cursor = 0- processed = 0- extended = 0- skipped = 0-- while True:- cursor, keys = redis_client.scan(cursor, match=pattern, count=batch_size)-- for key in keys:- processed += 1-- # Get current TTL- current_ttl = redis_client.ttl(key)-- # Skip if key has no TTL (-1) or doesn't exist (-2)- if current_ttl < 0:- skipped += 1- logger.debug(f"Skipping key {key}: TTL={current_ttl}")- continue-- # Calculate new TTL- new_ttl = current_ttl + extension_seconds-- if dry_run:- logger.info(f"[DRY RUN] Would extend {key}: {current_ttl}s → {new_ttl}s (+{extension_seconds}s)")- extended += 1- else:- # Extend the TTL- redis_client.expire(key, new_ttl)- logger.info(f"Extended {key}: {current_ttl}s → {new_ttl}s")- extended += 1-- # Report progress every batch- if processed > 0 and processed % batch_size == 0:- self.stdout.write(f" Progress: {processed} keys processed...")-- # Break when scan completes- if cursor == 0:- break-- return processed, extended, skippeddiff --git a/posthog/management/commands/test/test_add_question_ids_to_surveys.py b/posthog/management/commands/test/test_add_question_ids_to_surveys.pydeleted file mode 100644index 604018ecd52a..000000000000--- a/posthog/management/commands/test/test_add_question_ids_to_surveys.py+++ /dev/null@@ -1,142 +0,0 @@-from posthog.test.base import BaseTest-from unittest.mock import patch--from django.core.management import call_command-from django.db.models.signals import pre_save--from products.surveys.backend.models import Survey, pre_save_survey---class TestAddQuestionIdsToSurveys(BaseTest):- def setUp(self):- super().setUp()-- # Disconnect the pre_save signal temporarily to create surveys without IDs- pre_save.disconnect(pre_save_survey, sender=Survey)-- # Create test surveys with and without question IDs- self.survey1 = Survey.objects.create(- team=self.team,- name="Survey with IDs",- questions=[- {"id": "existing-id-1", "type": "open", "question": "What do you think?"},- {"id": "existing-id-2", "type": "rating", "question": "How would you rate us?"},- ],- )-- self.survey2 = Survey.objects.create(- team=self.team,- name="Survey without IDs",- questions=[- {"type": "open", "question": "What do you think?"},- {"type": "rating", "question": "How would you rate us?"},- ],- )-- self.survey3 = Survey.objects.create(- team=self.team,- name="Survey with mixed IDs",- questions=[- {"id": "existing-id-3", "type": "open", "question": "What do you think?"},- {"type": "rating", "question": "How would you rate us?"},- ],- )-- self.survey4 = Survey.objects.create(- team=self.team,- name="Survey with no questions",- questions=[],- )-- # Reconnect the pre_save signal- pre_save.connect(pre_save_survey, sender=Survey)-- def test_add_question_ids_to_surveys_with_really_run(self):- # Run the command with really-run flag- call_command("add_question_ids_to_surveys", batch_size=2, really_run=True)-- # Refresh surveys from database- self.survey1.refresh_from_db()- self.survey2.refresh_from_db()- self.survey3.refresh_from_db()- self.survey4.refresh_from_db()-- # Check that all questions have IDs- assert self.survey1.questions is not None- for question in self.survey1.questions:- self.assertIn("id", question)- # Original IDs should be preserved- if question["question"] == "What do you think?":- self.assertEqual(question["id"], "existing-id-1")- elif question["question"] == "How would you rate us?":- self.assertEqual(question["id"], "existing-id-2")-- assert self.survey2.questions is not None- for question in self.survey2.questions:- self.assertIn("id", question)- # These should have new UUIDs- self.assertTrue(len(question["id"]) > 0)-- assert self.survey3.questions is not None- for question in self.survey3.questions:- self.assertIn("id", question)- # First question should keep its ID- if question["question"] == "What do you think?":- self.assertEqual(question["id"], "existing-id-3")- # Second question should have a new UUID- elif question["question"] == "How would you rate us?":- self.assertTrue(len(question["id"]) > 0)-- # Survey with no questions should remain unchanged- self.assertEqual(self.survey4.questions, [])-- def test_default_dry_run_mode(self):- # Run the command without really-run flag (default dry-run mode)- call_command("add_question_ids_to_surveys", batch_size=2)-- # Refresh surveys from database- self.survey2.refresh_from_db()-- # Check that no changes were made in dry-run mode- assert self.survey2.questions is not None- for question in self.survey2.questions:- self.assertNotIn("id", question)-- def test_batch_processing(self):- """- Test that the command processes surveys in batches as expected.-- This test verifies that the command works correctly with a very small batch size,- which indirectly confirms that batch processing is working.- """- # Create additional surveys for this test- pre_save.disconnect(pre_save_survey, sender=Survey)-- # Create 10 surveys without question IDs for this test- for i in range(10):- Survey.objects.create(- team=self.team,- name=f"Batch Test Survey {i}",- questions=[- {"type": "open", "question": f"Question {i}"},- ],- )-- pre_save.connect(pre_save_survey, sender=Survey)-- # Set a very small batch size to ensure multiple batches- batch_size = 1-- # Run the command with a small batch size- with patch("sys.stdout"):- call_command("add_question_ids_to_surveys", batch_size=batch_size, really_run=True)-- # Verify that all surveys have question IDs now- for survey in Survey.objects.filter(name__startswith="Batch Test Survey"):- survey.refresh_from_db()- for question in survey.questions:- self.assertIn("id", question)- self.assertTrue(len(question["id"]) > 0)-- # The fact that all surveys were processed with a batch size of 1- # indirectly confirms that the batch processing logic works correctlydiff --git a/posthog/management/commands/test/test_backfill_user_joined_notification_settings.py b/posthog/management/commands/test/test_backfill_user_joined_notification_settings.pydeleted file mode 100644index 366fd780b525..000000000000--- a/posthog/management/commands/test/test_backfill_user_joined_notification_settings.py+++ /dev/null@@ -1,83 +0,0 @@-import uuid-from io import StringIO--from posthog.test.base import BaseTest--from django.core.management import call_command--from posthog.management.commands.backfill_user_joined_notification_settings import ORG_MEMBER_JOIN_KEY-from posthog.models import Organization---class TestBackfillUserJoinedNotificationSettingsCommand(BaseTest):- def setUp(self) -> None:- super().setUp()- self.stdout = StringIO()-- def test_backfill_sets_flags_from_org_is_member_join_email_enabled(self) -> None:- self.user.partial_notification_settings = {"plugin_disabled": False}- self.user.save()-- org_disabled = Organization.objects.create(- name="No join emails",- is_member_join_email_enabled=False,- )- self.user.join(organization=org_disabled)-- self.organization.is_member_join_email_enabled = True- self.organization.save()-- call_command("backfill_user_joined_notification_settings", stdout=self.stdout)-- self.user.refresh_from_db(fields=["partial_notification_settings"])- pns = self.user.partial_notification_settings or {}- self.assertEqual(pns.get("plugin_disabled"), False)- join_map = pns.get(ORG_MEMBER_JOIN_KEY, {})- self.assertEqual(join_map[str(self.organization.id)], False)- self.assertEqual(join_map[str(org_disabled.id)], True)-- def test_dry_run_does_not_write(self) -> None:- self.user.partial_notification_settings = None- self.user.save()-- call_command("backfill_user_joined_notification_settings", "--dry-run", stdout=self.stdout)-- self.user.refresh_from_db(fields=["partial_notification_settings"])- self.assertIsNone(self.user.partial_notification_settings)-- def test_backfill_preserves_other_top_level_notification_keys(self) -> None:- before = {- "plugin_disabled": False,- "discussions_mentioned": False,- "all_weekly_digest_disabled": True,- "data_pipeline_error_threshold": 0.05,- "project_weekly_digest_disabled": {str(self.team.id): True},- "error_tracking_weekly_digest_project_enabled": {str(self.team.id): True},- }- self.user.partial_notification_settings = dict(before)- self.user.save()-- call_command("backfill_user_joined_notification_settings", stdout=self.stdout)-- self.user.refresh_from_db(fields=["partial_notification_settings"])- pns = self.user.partial_notification_settings or {}- for key, value in before.items():- self.assertEqual(pns.get(key), value, msg=f"expected {key!r} unchanged")- join_map = pns.get(ORG_MEMBER_JOIN_KEY, {})- self.assertEqual(join_map[str(self.organization.id)], False)-- def test_backfill_skips_users_who_already_have_join_notification_key(self) -> None:- stale_org_id = str(uuid.uuid4())- self.user.partial_notification_settings = {- ORG_MEMBER_JOIN_KEY: {- stale_org_id: True,- },- }- self.user.save()-- call_command("backfill_user_joined_notification_settings", stdout=self.stdout)-- self.user.refresh_from_db(fields=["partial_notification_settings"])- join_map = (self.user.partial_notification_settings or {}).get(ORG_MEMBER_JOIN_KEY, {})- self.assertEqual(join_map.get(stale_org_id), True)- self.assertNotIn(str(self.organization.id), join_map)