: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
feat(cdp): migrate legacy site app plugins to hog functions (#97431)
Ben White393ef6a9ffd8
diff --git a/posthog/cdp/migrations.py b/posthog/cdp/migrations.pyindex 8f330ad4fc87..8e439a9b96b0 100644--- a/posthog/cdp/migrations.py+++ b/posthog/cdp/migrations.py@@ -1,21 +1,62 @@import json+from collections.abc import Mapping+from functools import partialfrom typing import Anyfrom django.db import transactionfrom django.db.models import Qfrom posthog.models.team.team import Team+from posthog.plugins.site import get_site_config_from_schema+from posthog.tasks.remote_config import update_team_remote_configfrom products.cdp.backend.api.hog_function import HogFunctionSerializerfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction-from products.cdp.backend.models.plugin import PluginAttachment, PluginConfig+from products.cdp.backend.models.plugin import PluginAttachment, PluginConfig, PluginSourceFile# python manage.py migrate_plugins_to_hog_functions --dry-run --test-mode --kind=transformation+# Site apps declare no capability methods, so they are matched by repo slug+LEGACY_SITE_APP_TEMPLATES: dict[str, str] = {+ "early-access-features-app": "template-early-access-features",+ "notification-bar-app": "template-notification-bar",+ "bug-report-app": "template-hogdesk",+ "pineapple-mode-app": "template-pineapple-mode",+}++_TRUTHY_STRINGS = {"yes", "true", "1"}+_FALSY_STRINGS = {"no", "false", "0", ""}+++def coerce_input_value(value: object, schema: Mapping[str, Any]) -> object:+ """Plugin configs store every value as a string, while hog function inputs are typed."""++ item_type = schema.get("type")++ if item_type == "boolean" and isinstance(value, str):+ lowered = value.strip().lower()+ if lowered in _TRUTHY_STRINGS:+ return True+ if lowered in _FALSY_STRINGS:+ return False++ if item_type == "string" and value is not None and not isinstance(value, str):+ return str(value)++ return value+def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: bool):hog_functions = []+ # A config may be disabled once something replaces it, whether that is a hog function this run+ # created or one that already existed. A config we skipped for having no template is still+ # serving the customer, so disabling it would take it away with nothing in its place.+ covered_plugin_config_ids: list[int] = []+ affected_team_ids: set[int] = set()+ # bulk_create only runs at the end of the batch, so a second config of the same app would not+ # see the row the first one produced and would create the app twice.+ covered_pairs: set[tuple[int, str]] = set()teams_cache: dict[int, Team] = {}with transaction.atomic():@@ -46,12 +87,34 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: boolif test_mode:plugin_name = f"[CDP-TEST-HIDDEN] {plugin_name}"+ if kind == "site_app":+ template_id = LEGACY_SITE_APP_TEMPLATES.get(plugin_id)+ if not template_id:+ print(f"Skipping plugin {plugin_name} as it has no site app template") # noqa: T201+ continue+ else:+ template_id = f"plugin-{plugin_id}"++ template = HogFunctionTemplate.get_template(template_id)++ if not template:+ raise Exception(f"Template not found for plugin {plugin_id}")++ schemas_by_key = {schema["key"]: schema for schema in template.inputs_schema or [] if "key" in schema}++ if kind == "site_app":+ # A site app reads what the plugin schema resolves, which fills every unset key+ config = get_site_config_from_schema(plugin_config["plugin__config_schema"], plugin_config["config"])+ else:+ config = plugin_config["config"]+inputs = {}# Iterate over the plugin config to build the inputs- for key, value in plugin_config["config"].items():- inputs[key] = {"value": value}+ for key, value in config.items():+ schema = schemas_by_key.get(key)+ inputs[key] = {"value": coerce_input_value(value, schema) if schema else value}if plugin_id == "first-time-event-tracker" or plugin_id == "customerio-plugin":# These are plugins that use the legacy storage@@ -83,15 +146,16 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: bool"is_create": True,}- template = HogFunctionTemplate.objects.get(template_id=f"plugin-{plugin_id}")-- if not template:- raise Exception(f"Template not found for plugin {plugin_id}")-- if HogFunction.objects.filter(- template_id=template.id, type=kind, team_id=team.id, enabled=True, deleted=False- ).exists():+ pair = (team.id, template.template_id)+ if (+ pair in covered_pairs+ or HogFunction.objects.filter(+ template_id=template.template_id, type=kind, team_id=team.id, enabled=True, deleted=False+ ).exists()+ ):print(f"Skipping plugin {plugin_name} as it already exists as a hog function") # noqa: T201+ covered_plugin_config_ids.append(plugin_config["id"])+ affected_team_ids.add(team.id)continuedata = {@@ -102,7 +166,8 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: bool"filters": template.filters,"hog": template.code,"inputs": inputs,- "enabled": True,+ # A test-mode site app would render on the customer's site next to the plugin it copies+ "enabled": not (test_mode and kind == "site_app"),"icon_url": template.icon_url,"inputs_schema": template.inputs_schema,"execution_order": plugin_config["order"],@@ -117,10 +182,13 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: bool)serializer.is_valid(raise_exception=True)hog_functions.append(HogFunction(**serializer.validated_data))+ covered_plugin_config_ids.append(plugin_config["id"])+ covered_pairs.add(pair)+ affected_team_ids.add(team.id)print(hog_functions) # noqa: T201- if not hog_functions:+ if not hog_functions and not covered_plugin_config_ids:print("No hog functions to create") # noqa: T201return []@@ -135,9 +203,14 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: boolprint("Disabling old plugins") # noqa: T201# Disable the old plugins# nosemgrep: idor-lookup-without-team (internal migration; IDs from prior team-scoped query)- PluginConfig.objects.filter(id__in=[plugin_config["id"] for plugin_config in legacy_plugins]).update(- enabled=False- )+ PluginConfig.objects.filter(id__in=covered_plugin_config_ids).update(enabled=False)++ if kind == "site_app":+ # bulk_create and queryset.update() skip the post_save receivers that rebuild the+ # team's remote config, so the browser would keep serving the old site app. Disabling a+ # config changes what is served even when this run created nothing for that team.+ for team_id in affected_team_ids:+ transaction.on_commit(partial(update_team_remote_config.delay, team_id))print("Done") # noqa: T201@@ -159,6 +232,11 @@ def migrate_legacy_plugins()elif kind == "transformation":legacy_plugin_ids = legacy_plugin_ids.filter(plugin__capabilities__methods__contains=["processEvent"])+ elif kind == "site_app":+ legacy_plugin_ids = legacy_plugin_ids.filter(+ plugin__pluginsourcefile__filename="site.ts",+ plugin__pluginsourcefile__status=PluginSourceFile.Status.TRANSPILED,+ )else:raise ValueError(f"Invalid kind: {kind}")diff --git a/posthog/cdp/site_functions.py b/posthog/cdp/site_functions.pyindex c16d975b21e1..77f179fde531 100644--- a/posthog/cdp/site_functions.py+++ b/posthog/cdp/site_functions.py@@ -24,10 +24,20 @@ def get_transpiled_function(hog_function: HogFunction) -> str:all_inputs = hog_function.inputs or {}all_inputs = sorted(all_inputs.items(), key=lambda x: x[1].get("order", -1))+ # Without this, CSS and HTML braces in a literal string read as Hog placeholders+ literal_keys = {+ schema["key"]+ for schema in hog_function.inputs_schema or []+ if "key" in schema and schema.get("templating") is False+ }for key, input in all_inputs:value = input.get("value")key_string = json.dumps(str(key) or "<empty>")- if (isinstance(value, str) and "{" in value) or isinstance(value, dict) or isinstance(value, list):+ if (+ (isinstance(value, str) and "{" in value and key not in literal_keys)+ or isinstance(value, dict)+ or isinstance(value, list)+ ):base_code = transpile_template_code(value, compiler)inputs_switch += f"case {key_string}: return {base_code};\n"inputs_append.append(f"inputs[{key_string}] = getInputsKey({json.dumps(key)});")diff --git a/posthog/cdp/templates/_siteapps/template_notification_bar.py b/posthog/cdp/templates/_siteapps/template_notification_bar.pyindex 46fd1bdf0608..6061dc988f28 100644--- a/posthog/cdp/templates/_siteapps/template_notification_bar.py+++ b/posthog/cdp/templates/_siteapps/template_notification_bar.py@@ -51,6 +51,7 @@ export function onLoad({ inputs }) {.notification-bar p {margin: 0;}+ ${inputs.cssOverride || ''}`const paragraph = Object.assign(document.createElement('p'), {innerHTML: inputs.notification,@@ -158,5 +159,14 @@ function createShadowRoot(style) {"default": "yes","description": "Remember if the user has closed the notification bar, and don't show it again. This resets if you update the notification bar's text.",},+ {+ "key": "cssOverride",+ "label": "Custom CSS",+ "type": "string",+ "default": "",+ "description": 'CSS added to the notification bar. For example: ".notification-bar { font-size: 16px }"',+ # CSS braces are not Hog placeholders+ "templating": False,+ },],)diff --git a/posthog/cdp/test/test_migrations.py b/posthog/cdp/test/test_migrations.pynew file mode 100644index 000000000000..0bbee694d09d--- /dev/null+++ b/posthog/cdp/test/test_migrations.py@@ -0,0 +1,166 @@+import dataclasses++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.cdp.migrations import coerce_input_value, migrate_legacy_plugins+from posthog.cdp.templates._siteapps.template_notification_bar import template as notification_bar+from posthog.cdp.templates._siteapps.template_pineapple_mode import template as pineapple_mode+from posthog.cdp.templates.helpers import mock_transpile+from posthog.cdp.templates.hog_function_template import sync_template_to_db++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginSourceFile+++class TestCoerceInputValue(SimpleTestCase):+ @parameterized.expand(+ [+ ("boolean_yes", {"type": "boolean"}, "Yes", True),+ ("boolean_no", {"type": "boolean"}, "No", False),+ ("boolean_empty", {"type": "boolean"}, "", False),+ ("boolean_untouched", {"type": "boolean"}, True, True),+ ("boolean_unknown_string", {"type": "boolean"}, "maybe", "maybe"),+ ("string_from_number", {"type": "string"}, 999999, "999999"),+ ("string_untouched", {"type": "string"}, "sticky", "sticky"),+ ("choice_untouched", {"type": "choice"}, "Yes", "Yes"),+ ]+ )+ def test_coerce_input_value(self, _name, schema, value, expected):+ assert coerce_input_value(value, schema) == expected+++class TestMigrateSiteApps(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ sync_template_to_db(dataclasses.asdict(pineapple_mode))+ sync_template_to_db(dataclasses.asdict(notification_bar))++ self.plugin_config = self._create_site_app(+ "Pineapple Mode",+ "https://github.com/PostHog/pineapple-mode-app",+ {"emoji": "🍍", "intensity": "5", "showButton": "No", "startRaining": "Yes"},+ unset={"buttonText": "Rain!"},+ )++ def _create_site_app(+ self, name: str, url: str, config: dict[str, str], unset: dict[str, str] | None = None+ ) -> PluginConfig:+ config_schema = [{"key": key, "type": "string", "site": True} for key in config]+ config_schema += [+ {"key": key, "type": "string", "site": True, "default": v} for key, v in (unset or {}).items()+ ]++ plugin = Plugin.objects.create(+ organization=self.team.organization,+ name=name,+ plugin_type="custom",+ url=url,+ config_schema=config_schema,+ )+ PluginSourceFile.objects.create(+ plugin=plugin,+ filename="site.ts",+ source="export function inject (){}",+ transpiled="function inject(){}",+ status=PluginSourceFile.Status.TRANSPILED,+ )+ return PluginConfig.objects.create(+ plugin=plugin,+ enabled=True,+ order=1,+ team=self.team,+ config=config,+ web_token=f"token-{name}",+ )++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_migrates_site_app_plugin_to_hog_function(self, mock_transpile_fn):+ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")++ hog_function = HogFunction.objects.get(team=self.team)+ assert hog_function.type == "site_app"+ assert hog_function.template_id == "template-pineapple-mode"+ assert hog_function.enabled++ inputs = hog_function.inputs or {}+ assert inputs["emoji"]["value"] == "🍍"+ assert inputs["intensity"]["value"] == "5"+ # The team never set this, so the plugin schema default is what the site app was showing+ assert inputs["buttonText"]["value"] == "Rain!"+ # The plugin stored these as choice strings, the template reads them as booleans+ assert inputs["showButton"]["value"] is False+ assert inputs["startRaining"]["value"] is True++ self.plugin_config.refresh_from_db()+ assert not self.plugin_config.enabled++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_migrates_notification_bar_custom_css(self, mock_transpile_fn):+ css = ".notification-bar { font-size: 16px }"+ notification_bar_config = self._create_site_app(+ "Notification Bar",+ "https://github.com/PostHog/notification-bar-app",+ {"notification": "Hello", "position": "sticky", "cssOverride": css},+ )++ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")++ hog_function = HogFunction.objects.get(team=self.team, template_id="template-notification-bar")+ # Braces in the CSS must survive as literal text rather than compile as Hog placeholders+ assert (hog_function.inputs or {})["cssOverride"]["value"] == css+ assert css in (hog_function.transpiled or "")++ notification_bar_config.refresh_from_db()+ assert not notification_bar_config.enabled++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_leaves_a_site_app_with_no_template_enabled(self, mock_transpile_fn):+ # Disabling one of these would take it off the customer's site with nothing to replace it+ unsupported = self._create_site_app(+ "Custom Thing",+ "https://github.com/PostHog/custom-thing-app",+ {"greeting": "Hi"},+ )++ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")++ unsupported.refresh_from_db()+ assert unsupported.enabled+ assert not HogFunction.objects.filter(team=self.team, name="Custom Thing").exists()+ # The supported one in the same batch still migrates+ self.plugin_config.refresh_from_db()+ assert not self.plugin_config.enabled++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_disables_a_second_config_of_an_app_already_covered(self, mock_transpile_fn):+ # Teams do run the same site app twice. The second one is replaced by the hog function the+ # first produced, so leaving it enabled would render the app twice.+ second = PluginConfig.objects.create(+ plugin=self.plugin_config.plugin,+ enabled=True,+ order=2,+ team=self.team,+ config=self.plugin_config.config,+ web_token="token-second",+ )++ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")++ assert HogFunction.objects.filter(team=self.team, template_id="template-pineapple-mode").count() == 1+ second.refresh_from_db()+ self.plugin_config.refresh_from_db()+ assert not second.enabled+ assert not self.plugin_config.enabled++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_migration_is_idempotent(self, mock_transpile_fn):+ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")+ PluginConfig.objects.filter(id=self.plugin_config.id).update(enabled=True)+ migrate_legacy_plugins(dry_run=False, test_mode=False, kind="site_app")++ assert HogFunction.objects.filter(team=self.team).count() == 1diff --git a/posthog/cdp/test/test_site_functions.py b/posthog/cdp/test/test_site_functions.pyindex 07f671b02e8a..ac436046611d 100644--- a/posthog/cdp/test/test_site_functions.py+++ b/posthog/cdp/test/test_site_functions.py@@ -147,6 +147,28 @@ class TestSiteFunctions(TestCase):assert '"staticMessage": "This is a static message."' in resultassert "function getInputsKey" not in result+ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_get_transpiled_function_with_templating_disabled(self, mock_transpile_fn):+ self.hog_function.hog = "export function onLoad() { console.log(inputs.cssOverride); }"+ self.hog_function.inputs_schema = [{"key": "cssOverride", "type": "string", "templating": False}]+ self.hog_function.inputs = {"cssOverride": {"value": ".bar { color: red }"}}++ result = self.compile_and_run()++ assert '"cssOverride": ".bar { color: red }"' in result+ assert "function getInputsKey" not in result++ @patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)+ def test_get_transpiled_function_with_templating_disabled_on_a_list(self, mock_transpile_fn):+ self.hog_function.hog = "export function onLoad() { console.log(inputs.notices); }"+ self.hog_function.inputs_schema = [{"key": "notices", "type": "json", "templating": False}]+ self.hog_function.inputs = {"notices": {"value": [{"id": "{event.properties.id}"}]}}++ result = self.compile_and_run()++ # Only strings opt out of templating, so a structured value still compiles+ assert "function getInputsKey" in result+@patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile)def test_get_transpiled_function_with_list_inputs(self, mock_transpile_fn):self.hog_function.hog = "export function onLoad() { console.log(inputs.messages); }"diff --git a/posthog/management/commands/migrate_plugins_to_hog_functions.py b/posthog/management/commands/migrate_plugins_to_hog_functions.pyindex f4569270a036..42b3428b9852 100644--- a/posthog/management/commands/migrate_plugins_to_hog_functions.py+++ b/posthog/management/commands/migrate_plugins_to_hog_functions.py@@ -19,8 +19,8 @@ class Command(BaseCommand):parser.add_argument("--kind",type=str,- help="Whether to migrate destinations or transformations",- choices=["destination", "transformation"],+ help="Whether to migrate destinations, transformations or site apps",+ choices=["destination", "transformation", "site_app"],)parser.add_argument("--batch-size", type=int, help="The number of plugins to migrate at a time", default=100)parser.add_argument("--limit", type=int, help="The number of plugins to migrate", default=None)diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex efd45455dc73..022ed056a035 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -715,12 +715,14 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):if hog_type in TYPES_WITH_JAVASCRIPT_SOURCE:try:# Validate transpilation using the model instance+ instance = self.instance if isinstance(self.instance, HogFunction) else Noneattrs["transpiled"] = get_transpiled_function(HogFunction(team=team,hog=attrs["hog"],filters=attrs["filters"],inputs=attrs["inputs"],+ inputs_schema=attrs.get("inputs_schema", instance.inputs_schema if instance else None),))except TranspilerError: