: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): add native Flatten Properties transformation (#93974)
Meikel Ratz084efab00275
diff --git a/nodejs/src/cdp/hog-transformations/transformation-functions.test.ts b/nodejs/src/cdp/hog-transformations/transformation-functions.test.tsindex bb43d2146cb6..7fb5aee2adee 100644--- a/nodejs/src/cdp/hog-transformations/transformation-functions.test.ts+++ b/nodejs/src/cdp/hog-transformations/transformation-functions.test.ts@@ -1,56 +1,124 @@-import { MAX_USER_AGENT_LENGTH, parseUserAgent } from './transformation-functions'+import { MAX_USER_AGENT_LENGTH, flattenProperties, parseUserAgent } from './transformation-functions'const CHROME_UA ='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'-describe('parseUserAgent', () => {- it('parses a real user agent', () => {- expect(parseUserAgent(CHROME_UA)).toEqual({- browser: 'chrome',- browserVersion: '120.0.0',- os: 'Mac OS',- browserType: 'browser',- device: '',- deviceType: 'Desktop',+describe('transformation-functions', () => {+ describe('parseUserAgent', () => {+ it('parses a real user agent', () => {+ expect(parseUserAgent(CHROME_UA)).toEqual({+ browser: 'chrome',+ browserVersion: '120.0.0',+ os: 'Mac OS',+ browserType: 'browser',+ device: '',+ deviceType: 'Desktop',+ })})- })- it.each([- ['a non-string', 42],- ['an empty string', ''],- ])('returns null for %s', (_label, value) => {- expect(parseUserAgent(value)).toBeNull()- })+ it.each([+ ['a non-string', 42],+ ['an empty string', ''],+ ])('returns null for %s', (_label, value) => {+ expect(parseUserAgent(value)).toBeNull()+ })- it('returns null past the length bound without parsing', () => {- // Repeated `Chrom` tokens are the adversarial shape: detect-browser backtracks- // quadratically on them, so an unbounded value would stall the whole worker.- const hostile = 'Chrom'.repeat((100 * 1024) / 5)+ it('returns null past the length bound without parsing', () => {+ // Repeated `Chrom` tokens are the adversarial shape: detect-browser backtracks+ // quadratically on them, so an unbounded value would stall the whole worker.+ const hostile = 'Chrom'.repeat((100 * 1024) / 5)- const start = process.hrtime.bigint()- expect(parseUserAgent(hostile)).toBeNull()- const durationMs = Number(process.hrtime.bigint() - start) / 1e6+ const start = process.hrtime.bigint()+ expect(parseUserAgent(hostile)).toBeNull()+ const durationMs = Number(process.hrtime.bigint() - start) / 1e6- // Generous next to the ~1800ms an unbounded parse of this value costs, but tight enough- // to fail if the value ever reaches detect-browser again.- expect(durationMs).toBeLessThan(100)- })+ // Generous next to the ~1800ms an unbounded parse of this value costs, but tight enough+ // to fail if the value ever reaches detect-browser again.+ expect(durationMs).toBeLessThan(100)+ })++ it('parses a hostile value at the accepted maximum length quickly', () => {+ // The adversarial `Chrom` pattern at exactly the accepted maximum still reaches+ // detect-browser, so the bound must be low enough that even this stays cheap.+ const hostileAtMax = 'Chrom'.repeat(Math.floor(MAX_USER_AGENT_LENGTH / 5))- it('parses a hostile value at the accepted maximum length quickly', () => {- // The adversarial `Chrom` pattern at exactly the accepted maximum still reaches- // detect-browser, so the bound must be low enough that even this stays cheap.- const hostileAtMax = 'Chrom'.repeat(Math.floor(MAX_USER_AGENT_LENGTH / 5))+ const start = process.hrtime.bigint()+ parseUserAgent(hostileAtMax)+ const durationMs = Number(process.hrtime.bigint() - start) / 1e6- const start = process.hrtime.bigint()- parseUserAgent(hostileAtMax)- const durationMs = Number(process.hrtime.bigint() - start) / 1e6+ expect(durationMs).toBeLessThan(10)+ })- expect(durationMs).toBeLessThan(10)+ it('still parses a user agent at the length bound', () => {+ const padded = CHROME_UA + ' '.repeat(MAX_USER_AGENT_LENGTH - CHROME_UA.length)++ expect(parseUserAgent(padded)?.browser).toBe('chrome')+ })})- it('still parses a user agent at the length bound', () => {- const padded = CHROME_UA + ' '.repeat(MAX_USER_AGENT_LENGTH - CHROME_UA.length)+ describe('flattenProperties', () => {+ it('flattens nested objects and arrays, keeping originals and matching the legacy plugin', () => {+ expect(flattenProperties({ a: { b: { c: 1 } }, w: { arr: [{ z: 2 }] }, x: 'plain' }, '__')).toEqual({+ a: { b: { c: 1 } },+ w: { arr: [{ z: 2 }] },+ x: 'plain',+ a__b__c: 1,+ w__arr__0__z: 2,+ })+ })++ it('emits a nested empty object as a leaf but not an empty array', () => {+ expect(flattenProperties({ a: { b: {} }, list: { items: [] } }, '__')).toEqual({+ a: { b: {} },+ list: { items: [] },+ a__b: {},+ })+ })++ it('flattens within $set under a fresh prefix and skips internal properties', () => {+ const result = flattenProperties(+ { $set: { user: { id: 7 } }, $elements: { keep: 'nested' } },+ '__'+ ) as Record<string, any>- expect(parseUserAgent(padded)?.browser).toBe('chrome')+ expect(result.$set.user__id).toBe(7)+ expect(result.$elements__keep).toBeUndefined()+ })++ it('stays linear for a wide payload', () => {+ const wide: Record<string, any> = {}+ for (let i = 0; i < 50_000; i++) {+ wide[`k${i}`] = { nested: i }+ }+ const start = process.hrtime.bigint()+ const result = flattenProperties({ outer: wide }, '__') as Record<string, any>+ const durationMs = Number(process.hrtime.bigint() - start) / 1e6++ expect(result.outer__k49999__nested).toBe(49999)+ expect(durationMs).toBeLessThan(500)+ })++ it('falls back to the default separator when the configured one is too long', () => {+ // A huge separator would otherwise be copied into every flattened key.+ const result = flattenProperties({ a: { b: 1 } }, 'x'.repeat(200)) as Record<string, any>++ expect(result.a__b).toBe(1)+ })++ it('bounds total key bytes when a long property name sits above many leaves', () => {+ // A ~5000-char name over 2000 leaves would produce ~10MB of key strings; the byte+ // budget truncates before every leaf is flattened.+ const longName = 'p'.repeat(5000)+ const leaves = Array.from({ length: 2000 }, (_, i) => ({ x: i }))++ const result = flattenProperties({ [longName]: leaves }, '__') as Record<string, any>+ const flattenedKeys = Object.keys(result).filter((k) => k.startsWith(`${longName}__`))++ expect(flattenedKeys.length).toBeLessThan(2000)+ })++ it('returns the input unchanged when it is not an object', () => {+ expect(flattenProperties('nope', '__')).toBe('nope')+ })})})diff --git a/nodejs/src/cdp/hog-transformations/transformation-functions.ts b/nodejs/src/cdp/hog-transformations/transformation-functions.tsindex b8b72878d9bc..be1aaeead3d6 100644--- a/nodejs/src/cdp/hog-transformations/transformation-functions.ts+++ b/nodejs/src/cdp/hog-transformations/transformation-functions.ts@@ -118,6 +118,75 @@ export const parseUserAgent = (}}+// Internal properties used in event processing are left nested.+const FLATTEN_PROPERTY_DENYLIST = [+ '$elements',+ '$elements_chain',+ '$groups',+ '$active_feature_flags',+ '$heatmap_data',+ '$web_vitals_data',+]++// Real separators join keys and run a few characters. Cap the configured one so a huge value+// cannot be copied into every flattened key and blow up memory and CPU.+const MAX_SEPARATOR_LENGTH = 100+// Backstop on the number of flattened keys, so one pathological event cannot generate an unbounded+// number of properties. Well above any real event; capture already bounds the event size.+const MAX_FLATTENED_KEYS = 100000+// Backstop on the total bytes of generated keys. A long property name above many leaves would+// otherwise copy that prefix into every key, so a small payload could produce megabytes of keys.+const MAX_FLATTENED_KEY_BYTES = 5_000_000++// Flattening runs as a host function rather than in hog, because the hog VM re-costs a local on+// every read, which makes an in-language recursive flatten quadratic in the property count and can+// exhaust the transformation time budget. This accumulates in place, so it is linear.+function flattenPropertiesInternal(+ props: Record<string, any>,+ sep: string,+ nestedChain: string[],+ budget: { keys: number; bytes: number }+): Record<string, any> {+ const newProps: Record<string, any> = {}+ for (const [key, value] of Object.entries(props)) {+ if (budget.keys <= 0 || budget.bytes <= 0) {+ break+ }+ if (FLATTEN_PROPERTY_DENYLIST.includes(key)) {+ // Leave internal properties nested.+ } else if (key === '$set' || key === '$set_once' || key === '$group_set') {+ // A flattened key that collides with an existing one wins, matching the legacy plugin:+ // for `{$set: {a__b: 1, a: {b: 2}}}` the flattened `a__b: 2` replaces the literal `a__b: 1`.+ newProps[key] = { ...(props[key] as object), ...flattenPropertiesInternal(props[key], sep, [], budget) }+ } else if (+ Array.isArray(value) ||+ (value !== null && typeof value === 'object' && Object.keys(value).length > 0)+ ) {+ Object.assign(newProps, flattenPropertiesInternal(props[key], sep, [...nestedChain, key], budget))+ } else if (nestedChain.length > 0) {+ const flatKey = nestedChain.join(sep) + sep + key+ newProps[flatKey] = value+ budget.keys -= 1+ budget.bytes -= flatKey.length+ }+ }+ return nestedChain.length > 0 ? newProps : { ...props, ...newProps }+}++export const flattenProperties = (properties: unknown, separator?: unknown): unknown => {+ if (properties === null || typeof properties !== 'object' || Array.isArray(properties)) {+ return properties+ }+ let sep = typeof separator === 'string' && separator.length > 0 ? separator : '__'+ if (sep.length > MAX_SEPARATOR_LENGTH) {+ sep = '__'+ }+ return flattenPropertiesInternal(properties as Record<string, any>, sep, [], {+ keys: MAX_FLATTENED_KEYS,+ bytes: MAX_FLATTENED_KEY_BYTES,+ })+}+export const getTransformationFunctions = (geoipLookup: GeoIp) => {return {geoipLookup: (val: unknown): any => {@@ -127,6 +196,7 @@ export const getTransformationFunctions = (geoipLookup: GeoIp) => {isKnownBotUserAgent,isKnownBotIp,parseUserAgent,+ flattenProperties,postHogCapture: () => {throw new Error('posthogCapture is not supported in transformations')},diff --git a/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.ts b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.tsnew file mode 100644index 000000000000..1cfbea8748f2--- /dev/null+++ b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.test.ts@@ -0,0 +1,109 @@+import { HogFunctionInvocationGlobals } from '../../../types'+import { TemplateTester } from '../../test/test-helpers'+import { template } from './flatten-properties.template'++describe('flatten-properties.template', () => {+ const tester = new TemplateTester(template)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ const invoke = async (properties: Record<string, any>, event = 'test'): Promise<any> => {+ const globals: HogFunctionInvocationGlobals = tester.createGlobals({ event: { event, properties } })+ const response = await tester.invoke({ separator: '__' }, globals)+ expect(response.finished).toBe(true)+ expect(response.error).toBeUndefined()+ return (response.execResult as any).properties+ }++ it('flattens nested objects and arrays while keeping the originals', async () => {+ const properties = await invoke({+ a: { b: { c: { d: { e: { f: 'nested under e' }, z: 'nested under d' }, z: 'nested under c' } } },+ w: { array: [{ z: 'nested in w array' }] },+ x: 'not nested',+ })++ expect(properties.x).toBe('not nested')+ expect(properties.a).toEqual({+ b: { c: { d: { e: { f: 'nested under e' }, z: 'nested under d' }, z: 'nested under c' } },+ })+ expect(properties.a__b__c__d__e__f).toBe('nested under e')+ expect(properties.a__b__c__d__z).toBe('nested under d')+ expect(properties.a__b__c__z).toBe('nested under c')+ expect(properties.w__array__0__z).toBe('nested in w array')+ })++ it('flattens within $set and $set_once under a fresh prefix', async () => {+ const properties = await invoke({+ $set: { example: { company_size: 20, category: ['a', 'b'] } },+ $set_once: { example: { company_size: 20 } },+ })++ expect(properties.$set.example__company_size).toBe(20)+ expect(properties.$set.example__category__0).toBe('a')+ expect(properties.$set.example__category__1).toBe('b')+ expect(properties.$set.example).toEqual({ company_size: 20, category: ['a', 'b'] })+ expect(properties.$set_once.example__company_size).toBe(20)+ // The $set prefix is not carried into the flattened keys.+ expect(properties.$set__example__company_size).toBeUndefined()+ })++ it('keeps a separator for an empty property name so siblings survive', async () => {+ const properties = await invoke({+ name: 'kept',+ '': { name: 'nested under the empty key' },+ $set: { name: 'kept in $set', '': { name: 'nested under the empty key in $set' } },+ })++ expect(properties.name).toBe('kept')+ expect(properties.__name).toBe('nested under the empty key')+ expect(properties.$set.name).toBe('kept in $set')+ expect(properties.$set.__name).toBe('nested under the empty key in $set')+ })++ it('keeps a nested empty object as a flattened leaf', async () => {+ const properties = await invoke({+ a: { b: {} },+ list: { items: [] },+ $set: { a: { b: {} } },+ })++ expect(properties.a__b).toEqual({})+ expect(properties.$set.a__b).toEqual({})+ // An empty array has no items to enumerate, so it produces no flattened key.+ expect(properties.list__items).toBeUndefined()+ })++ it('leaves internal deny-listed properties nested', async () => {+ const properties = await invoke({+ $groups: { org: { id: 1 } },+ keep: { nested: 'value' },+ })++ expect(properties.$groups).toEqual({ org: { id: 1 } })+ expect(properties.$groups__org__id).toBeUndefined()+ expect(properties.keep__nested).toBe('value')+ })++ it('skips events on the event deny list', async () => {+ const properties = await invoke({ any: [{ nested: 'property' }] }, 'organization usage report')++ expect(properties).toEqual({ any: [{ nested: 'property' }] })+ })++ it('flattens a very wide payload in linear time', async () => {+ const wide: Record<string, any> = {}+ for (let i = 0; i < 5000; i++) {+ wide[`k${i}`] = { nested: i }+ }+ const start = performance.now()+ const properties = await invoke({ outer: wide })+ const elapsedMs = performance.now() - start++ expect(properties.outer__k0__nested).toBe(0)+ expect(properties.outer__k4999__nested).toBe(4999)+ // The host-side flatten is linear, so this stays well under the transformation time budget.+ expect(elapsedMs).toBeLessThan(2000)+ })+})diff --git a/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.ts b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.tsnew file mode 100644index 000000000000..a9c99a992a8a--- /dev/null+++ b/nodejs/src/cdp/templates/_transformations/flatten-properties/flatten-properties.template.ts@@ -0,0 +1,39 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ free: true,+ status: 'stable',+ type: 'transformation',+ id: 'template-flatten-properties',+ name: 'Flatten Properties',+ description:+ 'Flattens nested event properties into top-level keys joined by a separator, for example a.b.c becomes a__b__c.',+ icon_url: 'https://res.cloudinary.com/dmukukwp6/image/upload/q_auto,f_auto/builder_hog_01_955c082cad.png',+ category: ['Custom'],+ code_language: 'hog',+ code: `+// These events create very large numbers of flattened properties, so they are skipped.+if (event.event == '$autocapture' or event.event == 'organization usage report') {+ return event+}+if (empty(event.properties)) {+ return event+}++// The flatten runs as a host function so it stays linear in the property count. Doing it in hog+// is quadratic, because the VM re-costs a local on every read, and can hit the time budget.+let returnEvent := event+returnEvent.properties := flattenProperties(event.properties, inputs.separator)+return returnEvent+ `,+ inputs_schema: [+ {+ key: 'separator',+ type: 'string',+ label: 'Separator',+ description: 'The string used to join nested keys, for example __ turns a.b into a__b.',+ default: '__',+ required: true,+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex f01ac7ed8d4f..7bd3dbdd30cf 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -53,6 +53,7 @@ import { template as defaultTransformationTemplate } from './_transformations/deimport { template as downsamplingTemplate } from './_transformations/downsampling/downsampling.template'import { template as dropEventsTemplate } from './_transformations/drop-events/drop-events.template'import { template as filterPropertiesTemplate } from './_transformations/filter-properties/filter-properties.template'+import { template as flattenPropertiesTemplate } from './_transformations/flatten-properties/flatten-properties.template'import { template as geoipTemplate } from './_transformations/geoip/geoip.template'import { template as hashPropertiesTemplate } from './_transformations/hash-properties/hash-properties.template'import { template as ipAnonymizationTemplate } from './_transformations/ip-anonymization/ip-anonymization.template'@@ -134,6 +135,7 @@ export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS: HogFunctionTemplate[] = [urlParametersToPropertiesTemplate,taxonomyTemplate,userAgentTemplate,+ flattenPropertiesTemplate,]export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS_LOG: HogFunctionTemplate[] = [diff --git a/nodejs/tests/fixtures/hog-bytecode/097b79c51569e0d628f532b6c96bedb2b0ef0ed3dabc1a944495c530f616f02d.json b/nodejs/tests/fixtures/hog-bytecode/097b79c51569e0d628f532b6c96bedb2b0ef0ed3dabc1a944495c530f616f02d.jsonnew file mode 100644index 000000000000..0b9d6fc82c25--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/097b79c51569e0d628f532b6c96bedb2b0ef0ed3dabc1a944495c530f616f02d.json@@ -0,0 +1 @@+["_H",1,32,"$autocapture",32,"event",32,"event",1,2,11,32,"organization usage report",32,"event",32,"event",1,2,11,4,2,40,5,32,"event",1,1,38,32,"properties",32,"event",1,2,2,"empty",1,40,5,32,"event",1,1,38,32,"separator",32,"inputs",1,2,32,"$elements",32,"$elements_chain",32,"$groups",32,"$active_feature_flags",32,"$heatmap_data",32,"$web_vitals_data",43,6,52,"isContainer",1,0,33,31,36,0,12,32,"array",36,0,2,"typeof",1,11,32,"object",36,0,2,"typeof",1,11,36,0,2,"empty",1,5,3,2,4,2,3,2,38,53,0,52,"flattenInto",4,2,104,36,1,36,4,2,"keys",1,36,4,2,"values",1,33,1,36,6,2,"length",1,31,31,36,8,36,7,16,40,66,36,5,36,7,45,37,9,36,6,36,7,45,37,10,36,2,36,3,36,9,2,"toString",1,2,"concat",3,36,10,55,0,54,1,40,15,36,0,36,10,36,11,36,3,55,1,54,4,35,39,7,36,0,36,11,36,10,46,35,36,7,33,1,6,37,7,39,-73,35,35,35,35,35,35,35,36,0,38,53,2,true,2,true,3,32,"event",1,1,32,"properties",32,"event",1,2,42,0,36,5,36,7,2,"keys",1,36,7,2,"values",1,33,1,36,9,2,"length",1,31,31,36,11,36,10,16,40,71,36,8,36,10,45,37,12,36,9,36,10,45,37,13,36,1,36,12,2,"has",2,5,32,"$set",36,12,12,32,"$set_once",36,12,12,32,"$group_set",36,12,12,3,4,40,21,36,13,36,2,54,1,40,13,36,6,36,13,36,12,36,0,36,3,54,4,35,36,10,33,1,6,37,10,39,-78,35,35,35,35,35,35,35,36,6,36,7,2,"keys",1,36,7,2,"values",1,33,1,36,9,2,"length",1,31,31,36,11,36,10,16,40,33,36,8,36,10,45,37,12,36,9,36,10,45,37,13,36,4,32,"properties",45,36,12,36,13,46,36,10,33,1,6,37,10,39,-40,35,35,35,35,35,35,35,32,"$set",32,"$set_once",32,"$group_set",43,3,36,7,2,"values",1,33,1,36,8,2,"length",1,31,36,10,36,9,16,40,191,36,8,36,9,45,37,11,36,5,36,11,45,31,36,12,12,32,"object",36,12,2,"typeof",1,11,3,2,40,153,42,0,36,12,36,14,2,"keys",1,36,14,2,"values",1,33,1,36,16,2,"length",1,31,31,36,18,36,17,16,40,44,36,15,36,17,45,37,19,36,16,36,17,45,37,20,36,20,36,2,54,1,40,13,36,13,36,20,36,19,36,0,36,3,54,4,35,36,17,33,1,6,37,17,39,-51,35,35,35,35,35,35,35,36,13,36,14,2,"keys",1,36,14,2,"values",1,33,1,36,16,2,"length",1,31,31,36,18,36,17,16,40,36,36,15,36,17,45,37,19,36,16,36,17,45,37,20,36,4,32,"properties",45,36,11,45,36,19,36,20,46,36,17,33,1,6,37,17,39,-43,35,35,35,35,35,35,35,35,35,36,9,33,1,6,37,9,39,-198,35,35,35,35,35,36,4,38,35,35,35,57,57,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/bde1b79825fe00a3b7cdd603fd7bcd4c52ee1ab1e79983901bde2ecfd6b6ce4b.json b/nodejs/tests/fixtures/hog-bytecode/bde1b79825fe00a3b7cdd603fd7bcd4c52ee1ab1e79983901bde2ecfd6b6ce4b.jsonnew file mode 100644index 000000000000..a356b13f26b8--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/bde1b79825fe00a3b7cdd603fd7bcd4c52ee1ab1e79983901bde2ecfd6b6ce4b.json@@ -0,0 +1 @@+["_H",1,32,"$autocapture",32,"event",32,"event",1,2,11,32,"organization usage report",32,"event",32,"event",1,2,11,4,2,40,5,32,"event",1,1,38,32,"properties",32,"event",1,2,2,"empty",1,40,5,32,"event",1,1,38,32,"event",1,1,36,0,32,"properties",32,"properties",32,"event",1,2,32,"separator",32,"inputs",1,2,2,"flattenProperties",2,46,36,0,38,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/e20c9a4143cf8cc81d689d2ea93ca88a6508c9d79edab8b9df5496620212d730.json b/nodejs/tests/fixtures/hog-bytecode/e20c9a4143cf8cc81d689d2ea93ca88a6508c9d79edab8b9df5496620212d730.jsonnew file mode 100644index 000000000000..b1b842530922--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/e20c9a4143cf8cc81d689d2ea93ca88a6508c9d79edab8b9df5496620212d730.json@@ -0,0 +1 @@+["_H",1,32,"__",38]