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 native Downsampling transformation (#93939)

Meikel Ratz30d0934e526a
diff --git a/nodejs/src/cdp/legacy-plugins/_transformations/downsampling-plugin/template.ts b/nodejs/src/cdp/legacy-plugins/_transformations/downsampling-plugin/template.ts
index b5e1b41d0682..6461d8b2d9a2 100644
--- a/nodejs/src/cdp/legacy-plugins/_transformations/downsampling-plugin/template.ts
+++ b/nodejs/src/cdp/legacy-plugins/_transformations/downsampling-plugin/template.ts
@@ -7,7 +7,7 @@ export const downsamplingPlugin: LegacyTransformationPlugin = {
setupPlugin: setupPlugin as any,
template: {
free: true,
- status: 'stable',
+ status: 'deprecated',
type: 'transformation',
id: 'plugin-downsampling-plugin',
name: 'Downsample',
diff --git a/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.test.ts b/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.test.ts
new file mode 100644
index 000000000000..8b783ee126f8
--- /dev/null
+++ b/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.test.ts
@@ -0,0 +1,52 @@
+import { HogFunctionInvocationGlobals } from '../../../types'
+import { TemplateTester } from '../../test/test-helpers'
+import { template } from './downsampling.template'
+
+describe('downsampling.template', () => {
+ const tester = new TemplateTester(template)
+
+ beforeEach(async () => {
+ await tester.beforeEach()
+ })
+
+ const run = async (inputs: Record<string, any>, globals: HogFunctionInvocationGlobals) => {
+ const response = await tester.invoke(inputs, globals)
+ expect(response.finished).toBe(true)
+ expect(response.error).toBeUndefined()
+ return response.execResult
+ }
+
+ it('keeps every event at 100 percent', async () => {
+ const globals = tester.createGlobals({ event: { distinct_id: 'user-1', properties: {} } })
+ const result = await run({ percentage: 100 }, globals)
+ expect(result).toBeTruthy()
+ })
+
+ it('drops every event at 0 percent', async () => {
+ const globals = tester.createGlobals({ event: { distinct_id: 'user-1', properties: {} } })
+ const result = await run({ percentage: 0 }, globals)
+ expect(result).toBeFalsy()
+ })
+
+ it('is stable for a given distinct ID and monotonic as the percentage grows', async () => {
+ const globals = tester.createGlobals({ event: { distinct_id: 'user-stable', properties: {} } })
+
+ const keptAt = async (percentage: number): Promise<boolean> => Boolean(await run({ percentage }, globals))
+
+ // Two runs at the same percentage agree (no randomness in stable mode).
+ expect(await keptAt(50)).toBe(await keptAt(50))
+ // Once kept at some percentage, still kept at a higher one.
+ if (await keptAt(50)) {
+ expect(await keptAt(90)).toBe(true)
+ }
+ })
+
+ it('only samples the named triggering events', async () => {
+ const globals = tester.createGlobals({
+ event: { event: 'not_sampled', distinct_id: 'user-1', properties: {} },
+ })
+ // 0 percent would drop it, but it is not in the triggering list, so it is kept.
+ const result = await run({ percentage: 0, triggeringEvents: 'only_this_one' }, globals)
+ expect(result).toBeTruthy()
+ })
+})
diff --git a/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.ts b/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.ts
new file mode 100644
index 000000000000..10d9f670a80d
--- /dev/null
+++ b/nodejs/src/cdp/templates/_transformations/downsampling/downsampling.template.ts
@@ -0,0 +1,94 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+export const template: HogFunctionTemplate = {
+ free: true,
+ status: 'stable',
+ type: 'transformation',
+ id: 'template-downsampling',
+ name: 'Downsampling',
+ description:
+ 'Keeps only a percentage of events to reduce volume. Stable sampling keeps the same distinct IDs as the percentage grows; random sampling decides per event.',
+ icon_url: 'https://res.cloudinary.com/dmukukwp6/image/upload/q_auto,f_auto/builder_hog_01_955c082cad.png',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
+// Only sample the events named here; empty means sample every event.
+let applies := true
+if (not empty(trim(inputs.triggeringEvents))) {
+ applies := false
+ for (let name in splitByString(',', inputs.triggeringEvents)) {
+ if (trim(name) == event.event) {
+ applies := true
+ }
+ }
+}
+
+if (not applies) {
+ return event
+}
+
+// Handle the boundaries directly so 0 drops every event and 100 keeps every event in both modes,
+// and an out-of-range percentage cannot keep or drop more than intended.
+if (inputs.percentage <= 0) {
+ return null
+}
+if (inputs.percentage >= 100) {
+ return event
+}
+
+let keep := true
+if (inputs.randomSampling) {
+ keep := (randomFloat() * 100) <= inputs.percentage
+} else {
+ // Map the distinct ID to a stable value in [0, 1] from its sha256 hash. A distinct ID kept
+ // at a lower percentage stays kept as the percentage grows.
+ let hex := sha256Hex(event.distinct_id)
+ let digits := '0123456789abcdef'
+ let acc := 0.0
+ let maxAcc := 0.0
+ let i := 1
+ while (i <= 13) {
+ let d := position(digits, substring(hex, i, 1)) - 1
+ if (d < 0) {
+ d := 0
+ }
+ acc := acc * 16 + d
+ maxAcc := maxAcc * 16 + 15
+ i := i + 1
+ }
+ keep := (acc / maxAcc) <= (inputs.percentage / 100)
+}
+
+if (keep) {
+ return event
+}
+return null
+ `,
+ inputs_schema: [
+ {
+ key: 'percentage',
+ type: 'number',
+ label: 'Percentage of events to keep',
+ description: 'A number between 0 and 100. 100 keeps every event, 0 drops every event.',
+ default: 100,
+ required: true,
+ },
+ {
+ key: 'randomSampling',
+ type: 'boolean',
+ label: 'Use random sampling',
+ description:
+ 'When off, sampling is stable per distinct ID, so raising the percentage only adds events. When on, each event is decided independently.',
+ default: false,
+ required: false,
+ },
+ {
+ key: 'triggeringEvents',
+ type: 'string',
+ label: 'Events to sample',
+ description: 'Comma-separated event names to sample. Leave empty to sample every event.',
+ default: '',
+ required: false,
+ },
+ ],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index d36c5eec580e..5ac2debd7c36 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -50,6 +50,7 @@ import { template as vercelLogDrainTemplate } from './_sources/vercel/vercel_log
import { template as incomingWebhookTemplate } from './_sources/webhook/incoming_webhook.template'
import { template as botDetectionTemplate } from './_transformations/bot-detection/bot-detection.template'
import { template as defaultTransformationTemplate } from './_transformations/default/default.template'
+import { 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 geoipTemplate } from './_transformations/geoip/geoip.template'
@@ -126,6 +127,7 @@ export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS: HogFunctionTemplate[] = [
urlNormalizationTemplate,
semverFlattenerTemplate,
timestampParserTemplate,
+ downsamplingTemplate,
]
export const HOG_FUNCTION_TEMPLATES_TRANSFORMATIONS_LOG: HogFunctionTemplate[] = [
diff --git a/nodejs/tests/fixtures/hog-bytecode/1db667baa4286b39179be3a8ae4a8242d0e4738e6e50b73bf3e9220b456bfcc7.json b/nodejs/tests/fixtures/hog-bytecode/1db667baa4286b39179be3a8ae4a8242d0e4738e6e50b73bf3e9220b456bfcc7.json
new file mode 100644
index 000000000000..4b9b7d339cb4
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/1db667baa4286b39179be3a8ae4a8242d0e4738e6e50b73bf3e9220b456bfcc7.json
@@ -0,0 +1 @@
+["_H",1,29,32,"triggeringEvents",32,"inputs",1,2,2,"trim",1,2,"empty",1,5,40,72,30,37,0,32,",",32,"triggeringEvents",32,"inputs",1,2,2,"splitByString",2,36,1,2,"values",1,33,1,36,2,2,"length",1,31,36,4,36,3,16,40,33,36,2,36,3,45,37,5,32,"event",32,"event",1,2,36,5,2,"trim",1,11,40,3,29,37,0,36,3,33,1,6,37,3,39,-40,35,35,35,35,35,36,0,5,40,5,32,"event",1,1,38,33,0,32,"percentage",32,"inputs",1,2,16,40,2,31,38,33,100,32,"percentage",32,"inputs",1,2,14,40,5,32,"event",1,1,38,29,32,"randomSampling",32,"inputs",1,2,40,17,32,"percentage",32,"inputs",1,2,33,100,2,"randomFloat",0,8,16,37,1,39,104,32,"distinct_id",32,"event",1,2,2,"sha256Hex",1,32,"0123456789abcdef",34,0,34,0,33,1,33,13,36,6,16,40,58,33,1,36,3,36,2,36,6,33,1,2,"substring",3,2,"position",2,7,33,0,36,7,15,40,4,33,0,37,7,36,7,33,16,36,4,8,6,37,4,33,15,33,16,36,5,8,6,37,5,33,1,36,6,6,37,6,35,39,-65,33,100,32,"percentage",32,"inputs",1,2,9,36,5,36,4,9,16,37,1,35,35,35,35,35,36,1,40,5,32,"event",1,1,38,31,38,35,35]
diff --git a/nodejs/tests/fixtures/hog-bytecode/d940a23e3165a3a27a2daf29a9b5da86fc5a6dbeca28ad15fda1f377970eef75.json b/nodejs/tests/fixtures/hog-bytecode/d940a23e3165a3a27a2daf29a9b5da86fc5a6dbeca28ad15fda1f377970eef75.json
new file mode 100644
index 000000000000..a59dede6db31
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/d940a23e3165a3a27a2daf29a9b5da86fc5a6dbeca28ad15fda1f377970eef75.json
@@ -0,0 +1 @@
+["_H",1,32,"only_this_one",38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/f8fc8ad948e591955e2f56e667f43d4f087f511ffebdde6a2ddf021534a0affb.json b/nodejs/tests/fixtures/hog-bytecode/f8fc8ad948e591955e2f56e667f43d4f087f511ffebdde6a2ddf021534a0affb.json
new file mode 100644
index 000000000000..b39941b3eff5
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/f8fc8ad948e591955e2f56e667f43d4f087f511ffebdde6a2ddf021534a0affb.json
@@ -0,0 +1 @@
+["_H",1,29,32,"triggeringEvents",32,"inputs",1,2,2,"trim",1,2,"empty",1,5,40,72,30,37,0,32,",",32,"triggeringEvents",32,"inputs",1,2,2,"splitByString",2,36,1,2,"values",1,33,1,36,2,2,"length",1,31,36,4,36,3,16,40,33,36,2,36,3,45,37,5,32,"event",32,"event",1,2,36,5,2,"trim",1,11,40,3,29,37,0,36,3,33,1,6,37,3,39,-40,35,35,35,35,35,36,0,5,40,5,32,"event",1,1,38,29,32,"randomSampling",32,"inputs",1,2,40,17,32,"percentage",32,"inputs",1,2,33,100,2,"randomFloat",0,8,16,37,1,39,104,32,"distinct_id",32,"event",1,2,2,"sha256Hex",1,32,"0123456789abcdef",34,0,34,0,33,1,33,13,36,6,16,40,58,33,1,36,3,36,2,36,6,33,1,2,"substring",3,2,"position",2,7,33,0,36,7,15,40,4,33,0,37,7,36,7,33,16,36,4,8,6,37,4,33,15,33,16,36,5,8,6,37,5,33,1,36,6,6,37,6,35,39,-65,33,100,32,"percentage",32,"inputs",1,2,9,36,5,36,4,9,16,37,1,35,35,35,35,35,36,1,40,5,32,"event",1,1,38,31,38,35,35]