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.

feat(cdp): add legacy geoip transformation migration command (#69686)

José Sequeiraf3cb8d49f19e
diff --git a/posthog/management/commands/migrate_legacy_geoip_transformations.py b/posthog/management/commands/migrate_legacy_geoip_transformations.py
new file mode 100644
index 000000000000..e72ce76e8864
--- /dev/null
+++ b/posthog/management/commands/migrate_legacy_geoip_transformations.py
@@ -0,0 +1,115 @@
+import time
+
+from django.core.management.base import BaseCommand
+
+import structlog
+
+from posthog.cdp.validation import compile_hog
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+logger = structlog.get_logger(__name__)
+
+LEGACY_TEMPLATE_ID = "plugin-posthog-plugin-geoip"
+NEW_TEMPLATE_ID = "template-geoip"
+BATCH_SIZE = 1000
+
+
+class Command(BaseCommand):
+ help = "Migrate legacy plugin-posthog-plugin-geoip transformations in place to template-geoip"
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show what would be migrated without making changes",
+ )
+ parser.add_argument("--team-ids", type=str, help="Comma separated list of team ids to migrate")
+ parser.add_argument("--limit", type=int, default=None, help="Max number of transformations to migrate")
+
+ def handle(self, *args, **options):
+ dry_run = options.get("dry_run", False)
+ team_ids = options.get("team_ids")
+ limit = options.get("limit")
+ start_time = time.time()
+
+ template = HogFunctionTemplate.get_template(NEW_TEMPLATE_ID)
+ if not template:
+ self.stdout.write(self.style.ERROR(f"Template {NEW_TEMPLATE_ID} not found in the database, aborting"))
+ return
+
+ # All migrated rows get the same code, so compile once upfront
+ bytecode = compile_hog(template.code, "transformation")
+
+ queryset = HogFunction.objects.filter(
+ type="transformation",
+ template_id=LEGACY_TEMPLATE_ID,
+ deleted=False,
+ ).order_by("id")
+
+ if team_ids:
+ queryset = queryset.filter(team_id__in=[int(team_id) for team_id in team_ids.split(",")])
+
+ if limit is not None:
+ queryset = queryset[:limit]
+
+ # Snapshot the ids upfront: migrating a row removes it from the queryset's filter
+ # match set, so paginating the live queryset with OFFSET would skip rows
+ ids = list(queryset.values_list("id", flat=True))
+ total_found = len(ids)
+ migrated_count = 0
+ failed: list[tuple[str, int, str]] = []
+
+ if dry_run:
+ self.stdout.write(self.style.WARNING("DRY RUN - No changes will be made"))
+
+ self.stdout.write(f"Found {total_found} legacy GeoIP transformations to migrate")
+
+ for batch_start in range(0, total_found, BATCH_SIZE):
+ batch_ids = ids[batch_start : batch_start + BATCH_SIZE]
+
+ self.stdout.write(f"Processing batch of {len(batch_ids)} transformations...")
+
+ for hog_function in HogFunction.objects.filter(id__in=batch_ids).select_related("team").order_by("id"):
+ if dry_run:
+ migrated_count += 1
+ self.stdout.write(
+ f" Would migrate id={hog_function.id} team={hog_function.team_id} "
+ f"enabled={hog_function.enabled} name={hog_function.name!r}"
+ )
+ continue
+
+ # One broken row must not abort the whole run
+ try:
+ hog_function.template_id = NEW_TEMPLATE_ID
+ hog_function.hog = template.code
+ hog_function.bytecode = bytecode
+ hog_function.hog_function_template = template
+ hog_function.icon_url = template.icon_url
+ hog_function.save(
+ update_fields=[
+ "template_id",
+ "hog",
+ "bytecode",
+ "hog_function_template",
+ "icon_url",
+ "updated_at",
+ ]
+ )
+ migrated_count += 1
+ except Exception as e:
+ failed.append((str(hog_function.id), hog_function.team_id, str(e)))
+
+ duration = time.time() - start_time
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Migration completed in {duration:.2f}s. "
+ f"Found: {total_found}, Migrated: {migrated_count}, Failed: {len(failed)}"
+ )
+ )
+
+ if failed:
+ self.stdout.write(self.style.WARNING(f"{len(failed)} transformation(s) failed and were skipped:"))
+ for fn_id, team_id, error in failed:
+ self.stdout.write(f" id={fn_id} team={team_id} error={error}")
diff --git a/posthog/management/commands/test/test_migrate_legacy_geoip_transformations.py b/posthog/management/commands/test/test_migrate_legacy_geoip_transformations.py
new file mode 100644
index 000000000000..bcc4a9c2f3a8
--- /dev/null
+++ b/posthog/management/commands/test/test_migrate_legacy_geoip_transformations.py
@@ -0,0 +1,140 @@
+from io import StringIO
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+
+from posthog.cdp.validation import compile_hog
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
+GEOIP_TEMPLATE_CODE = """
+if (event.properties?.$geoip_disable or empty(event.properties?.$ip)) {
+ return event
+}
+return event
+"""
+
+
+class TestMigrateLegacyGeoipTransformations(BaseTest):
+ def setUp(self):
+ super().setUp()
+
+ self.template = HogFunctionTemplate.objects.create(
+ template_id="template-geoip",
+ name="GeoIP",
+ description="Adds geoip data to the event",
+ code=GEOIP_TEMPLATE_CODE,
+ code_language="hog",
+ inputs_schema=[],
+ type="transformation",
+ status="stable",
+ free=True,
+ icon_url="/static/transformations/geoip.png",
+ )
+
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ self.legacy_function = HogFunction.objects.create(
+ team=self.team,
+ name="My GeoIP",
+ type="transformation",
+ template_id="plugin-posthog-plugin-geoip",
+ hog="return event",
+ enabled=True,
+ execution_order=2,
+ icon_url="https://raw.githubusercontent.com/PostHog/posthog-plugin-geoip/main/logo.png",
+ filters={"events": [{"id": "$pageview", "type": "events"}]},
+ )
+ self.other_function = HogFunction.objects.create(
+ team=self.team,
+ name="Other transformation",
+ type="transformation",
+ template_id="plugin-downsampling-plugin",
+ hog="return event",
+ enabled=True,
+ )
+ self.deleted_function = HogFunction.objects.create(
+ team=self.team,
+ name="Deleted GeoIP",
+ type="transformation",
+ template_id="plugin-posthog-plugin-geoip",
+ hog="return event",
+ enabled=True,
+ deleted=True,
+ )
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_migrates_legacy_geoip_in_place_preserving_user_state(self, _mock_reload):
+ filters_before = HogFunction.objects.get(id=self.legacy_function.id).filters
+
+ out = StringIO()
+ call_command("migrate_legacy_geoip_transformations", stdout=out)
+
+ self.legacy_function.refresh_from_db()
+ assert self.legacy_function.template_id == "template-geoip"
+ assert self.legacy_function.hog == GEOIP_TEMPLATE_CODE
+ assert self.legacy_function.bytecode == compile_hog(GEOIP_TEMPLATE_CODE, "transformation")
+ assert self.legacy_function.hog_function_template_id == self.template.id
+ assert self.legacy_function.icon_url == "/static/transformations/geoip.png"
+
+ # User state must survive the migration untouched
+ assert self.legacy_function.name == "My GeoIP"
+ assert self.legacy_function.enabled is True
+ assert self.legacy_function.execution_order == 2
+ assert self.legacy_function.filters == filters_before
+
+ self.other_function.refresh_from_db()
+ assert self.other_function.template_id == "plugin-downsampling-plugin"
+ assert self.other_function.hog == "return event"
+
+ self.deleted_function.refresh_from_db()
+ assert self.deleted_function.template_id == "plugin-posthog-plugin-geoip"
+
+ output = out.getvalue()
+ self.assertIn("Found 1 legacy GeoIP transformations to migrate", output)
+ self.assertIn("Migrated: 1", output)
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_migrates_all_rows_across_batches(self, _mock_reload):
+ for i in range(2):
+ HogFunction.objects.create(
+ team=self.team,
+ name=f"GeoIP {i}",
+ type="transformation",
+ template_id="plugin-posthog-plugin-geoip",
+ hog="return event",
+ enabled=True,
+ )
+
+ out = StringIO()
+ with patch("posthog.management.commands.migrate_legacy_geoip_transformations.BATCH_SIZE", 1):
+ call_command("migrate_legacy_geoip_transformations", stdout=out)
+
+ assert not HogFunction.objects.filter(template_id="plugin-posthog-plugin-geoip", deleted=False).exists()
+ assert HogFunction.objects.filter(template_id="template-geoip").count() == 3
+ self.assertIn("Migrated: 3", out.getvalue())
+
+ def test_dry_run_makes_no_changes(self):
+ out = StringIO()
+ call_command("migrate_legacy_geoip_transformations", dry_run=True, stdout=out)
+
+ self.legacy_function.refresh_from_db()
+ assert self.legacy_function.template_id == "plugin-posthog-plugin-geoip"
+ assert self.legacy_function.hog == "return event"
+
+ output = out.getvalue()
+ self.assertIn("DRY RUN - No changes will be made", output)
+ self.assertIn("Migrated: 1", output)
+
+ def test_aborts_when_new_template_missing(self):
+ HogFunctionTemplate.objects.all().delete()
+
+ out = StringIO()
+ call_command("migrate_legacy_geoip_transformations", stdout=out)
+
+ self.legacy_function.refresh_from_db()
+ assert self.legacy_function.template_id == "plugin-posthog-plugin-geoip"
+
+ self.assertIn("Template template-geoip not found in the database, aborting", out.getvalue())