: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
fix(cdp): speed up property flattening and block deprecated templates (#93919)
Meikel Ratze03aaefcce41
diff --git a/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.test.ts b/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.test.tsindex dcb4a8e50355..83039c1a20af 100644--- a/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.test.ts+++ b/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.test.ts@@ -136,6 +136,26 @@ describe('the property flattener', () => {expect(eventsOutput.properties).toEqual(expectedProperties)})+ test('flattens many nested sibling objects in linear time', async () => {+ // This plugin runs synchronously on the ingestion consumer, so flattening must stay+ // linear in the number of properties. The bound is wide enough to not flake in CI+ // while still failing on a quadratic accumulator.+ const properties: Record<string, any> = {}+ for (let i = 0; i < 10_000; i++) {+ properties[`key${i}`] = { nested: i }+ }+ const event = createEvent({ event: 'test', properties })++ const start = performance.now()+ const eventsOutput = await processEvent(event, { config: { separator: '__' } })+ const elapsedMs = performance.now() - start++ expect(elapsedMs).toBeLessThan(3_000)+ expect(eventsOutput.properties['key0__nested']).toEqual(0)+ expect(eventsOutput.properties['key9999__nested']).toEqual(9999)+ expect(Object.keys(eventsOutput.properties)).toHaveLength(20_000)+ })+test('$group_set', async () => {const event = createEvent({event: '$groupidentify',diff --git a/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.ts b/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.tsindex a7fa9764fae1..0e9db3ba8b3a 100644--- a/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.ts+++ b/nodejs/src/cdp/legacy-plugins/_transformations/flatten-properties-plugin/index.ts@@ -31,20 +31,18 @@ const propertyDenyList = []const flattenProperties = (props: Record<string, any>, sep: string, nestedChain: string[] = []) => {- let newProps: Record<string, any> = {}+ // Accumulate with Object.assign: spreading the accumulator per key is O(N^2) in the+ // number of properties, and this runs synchronously on the ingestion consumer.+ const newProps: Record<string, any> = {}for (const [key, value] of Object.entries(props)) {if (propertyDenyList.includes(key)) {// Hide 'internal' properties used in event processing- } else if (key === '$set') {- newProps = { ...newProps, $set: { ...props[key], ...flattenProperties(props[key], sep) } }- } else if (key === '$set_once') {- newProps = { ...newProps, $set_once: { ...props[key], ...flattenProperties(props[key], sep) } }- } else if (key === '$group_set') {- newProps = { ...newProps, $group_set: { ...props[key], ...flattenProperties(props[key], sep) } }+ } else if (key === '$set' || key === '$set_once' || key === '$group_set') {+ newProps[key] = { ...props[key], ...flattenProperties(props[key], sep) }} else if (Array.isArray(value)) {- newProps = { ...newProps, ...flattenProperties(props[key], sep, [...nestedChain, key]) }+ Object.assign(newProps, flattenProperties(props[key], sep, [...nestedChain, key]))} else if (value !== null && typeof value === 'object' && Object.keys(value).length > 0) {- newProps = { ...newProps, ...flattenProperties(props[key], sep, [...nestedChain, key]) }+ Object.assign(newProps, flattenProperties(props[key], sep, [...nestedChain, key]))} else {if (nestedChain.length > 0) {newProps[nestedChain.join(sep) + `${sep}${key}`] = value@@ -52,7 +50,7 @@ const flattenProperties = (props: Record<string, any>, sep: string, nestedChain:}}if (nestedChain.length > 0) {- return { ...newProps }+ return newProps}return { ...props, ...newProps }}diff --git a/posthog/cdp/migrations.py b/posthog/cdp/migrations.pyindex 8f330ad4fc87..6871b5558cda 100644--- a/posthog/cdp/migrations.py+++ b/posthog/cdp/migrations.py@@ -81,6 +81,9 @@ def migrate_batch(legacy_plugins: Any, kind: str, test_mode: bool, dry_run: bool"team": team,"get_team": (lambda t=team: t),"is_create": True,+ # The plugin templates this migrates from are deprecated, which the serializer+ # otherwise blocks on create.+ "allow_deprecated_template": True,}template = HogFunctionTemplate.objects.get(template_id=f"plugin-{plugin_id}")diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 991cd1abf38d..2881f602fd0b 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -464,6 +464,15 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):"template_id": f"Template '{template.template_id}' is internal and cannot be used to create a function."})+ # Deprecated templates are only hidden from the template listing, so a direct API call with the+ # template id could still create one. Block that too; existing functions keep running, and the+ # legacy plugin migration (posthog/cdp/migrations.py) is the one internal caller allowed through.+ if template.status == "deprecated" and not self.context.get("allow_deprecated_template"):+ raise serializers.ValidationError(+ {+ "template_id": f"Template '{template.template_id}' is deprecated and cannot be used to create a new function."+ }+ )def _validate_hidden_template_not_enabled(self, attrs: dict, is_create: bool) -> None:# Creating from a hidden template is already blocked outright. For an existing function built fromdiff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex d80c58b780e4..7c4f6cce9f7f 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -348,6 +348,36 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.json()["attr"] == "template_id"assert not HogFunction.objects.filter(template_id="template-hidden-dest").exists()+ def test_create_from_deprecated_template_is_blocked(self):+ # Deprecated templates are excluded from the template listing but stay resolvable by id,+ # so the create path must reject them explicitly.+ HogFunctionTemplate.objects.create(+ template_id="plugin-deprecated-transformation",+ sha="1.0.0",+ name="Deprecated transformation",+ description="Legacy plugin",+ code="return event",+ code_language="hog",+ inputs_schema=[],+ type="transformation",+ status="deprecated",+ category=["Other"],+ free=True,+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_functions/",+ data={+ "type": "transformation",+ "name": "X",+ "template_id": "plugin-deprecated-transformation",+ "inputs": {},+ },+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "template_id"+ assert "deprecated" in response.json()["detail"]+ assert not HogFunction.objects.filter(template_id="plugin-deprecated-transformation").exists()+@parameterized.expand([# An existing hidden-template function (created before the create-path block) can be disabled