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): label filter errors by reason (#103788)

Meikel Ratz87dcf0e4ec95
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 48cef682ec52..297e28b0a229 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -58,6 +58,8 @@ export interface HogFunctionFilters {
properties?: Record<string, any>[] // Global property filters that apply to all events
filter_test_accounts?: boolean
bytecode?: HogBytecode
+ /** Set by Django when compilation failed. The bytecode is null beside it, unless the save kept the last working one. */
+ bytecode_error?: string
}
export type GroupType = {
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.test.ts b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
index 6f225f357310..4ca60ed651b1 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.test.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
@@ -1,3 +1,5 @@
+import { register } from 'prom-client'
+
import { ClickHouseTimestamp, ProjectId, RawClickHouseEvent } from '../../types'
import { HogFunctionFilterGlobals, HogFunctionInvocationGlobals, HogFunctionType } from '../types'
import {
@@ -240,6 +242,47 @@ describe('hog-function-filtering', () => {
})
})
+ describe('Filter error reasons', () => {
+ // All three labels, because the fn decides `type` and the call site decides `caller`. A
+ // count found by reason alone would still pass if either of those went wrong.
+ const errorCount = async (reason: string): Promise<number> => {
+ const metric = await register.getSingleMetric('cdp_hog_function_filter_error')?.get()
+ const sample = metric?.values.find(
+ ({ labels }) =>
+ labels.reason === reason &&
+ labels.type === 'destination' &&
+ labels.caller === 'build_hog_function_invocations'
+ )
+ return sample?.value ?? 0
+ }
+
+ // Without the label, a destination that floods the queue on its own and a filter that
+ // trips on some events read as one number.
+ it.each([
+ ['not_compiled', { bytecode_error: 'Cohort membership cannot be evaluated' }],
+ ['no_bytecode', {}],
+ // filter_test_accounts keeps the bytecode-only shortcut from returning before the VM runs.
+ ['vm_error', { bytecode: ['_H', 1, 999], filter_test_accounts: true }],
+ ])('reports %s', async (reason, filters) => {
+ const before = await errorCount(reason)
+
+ const result = await filterFunctionInstrumented({
+ caller: 'build_hog_function_invocations',
+ fn: {
+ id: 'test-function',
+ team_id: 1,
+ name: 'Test Function',
+ type: 'destination',
+ } as unknown as HogFunctionType,
+ filters: filters as HogFunctionType['filters'],
+ filterGlobals: { event: '$pageview' } as HogFunctionFilterGlobals,
+ })
+
+ expect(result.error).not.toBeUndefined()
+ expect(await errorCount(reason)).toBe(before + 1)
+ })
+ })
+
describe('Pre-filtering on event name', () => {
let mockHogFunction: HogFunctionType
let mockFilterGlobals: HogFunctionFilterGlobals
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.ts b/nodejs/src/cdp/utils/hog-function-filtering.ts
index ce94fb793a07..c16a7f3b5b85 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.ts
@@ -58,9 +58,16 @@ const hogFunctionFilterOutcomes = new Counter({
const hogFunctionFilterErrors = new Counter({
name: 'cdp_hog_function_filter_error',
help: 'A filter threw while being evaluated, by the code path that asked for it',
- labelNames: ['caller', 'type'],
+ labelNames: ['caller', 'type', 'reason'],
})
+/**
+ * `not_compiled` and `no_bytecode` break every event for a destination, the rest only the events
+ * whose shape the filter cannot handle. The thrown message never becomes a label, because it
+ * carries filter expressions and its cardinality is unbounded.
+ */
+type FilterErrorReason = 'not_compiled' | 'no_bytecode' | 'prefilter' | 'vm_error' | 'unknown'
+
const hogFunctionPreFilterCounter = new Counter({
name: 'cdp_hog_function_prefilter_result',
help: 'Count of pre-filter results',
@@ -403,6 +410,8 @@ export async function filterFunctionInstrumented(options: {
}
let preFilterMatch = null
+ // Narrows what the catch block can blame. Each step sets it before the call that can throw.
+ let reason: FilterErrorReason = 'unknown'
try {
// If there are no filters (only bytecode exists then on the filter object)
@@ -416,6 +425,7 @@ export async function filterFunctionInstrumented(options: {
// check whether we have a match with our pre-filter
// Only run if we have event filters and NO action filters (as actions are pre-saved event filters)
if (filters?.events?.length && !filters?.actions?.length) {
+ reason = 'prefilter'
preFilterMatch = preFilterResult(filters, filterGlobals)
if (preFilterMatch === false) {
hogFunctionPreFilterCounter.inc({ result: 'bytecode_execution_skipped__pre_filtered_out' })
@@ -432,9 +442,11 @@ export async function filterFunctionInstrumented(options: {
}
if (!filters?.bytecode) {
+ reason = filters?.bytecode_error ? 'not_compiled' : 'no_bytecode'
throw new Error('Filters were not compiled correctly and so could not be executed')
}
+ reason = 'vm_error'
const execHogOutcome = await execHog(filters.bytecode, { globals: filterGlobals })
if (execHogOutcome) {
@@ -475,7 +487,7 @@ export async function filterFunctionInstrumented(options: {
})
}
} catch (error) {
- hogFunctionFilterErrors.inc({ caller, type })
+ hogFunctionFilterErrors.inc({ caller, type, reason })
logger.debug('🦔', `[${fnKind}] Error filtering function`, {
functionId: fn.id,
diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.ts
index e6e2c2319012..643e966242db 100644
--- a/nodejs/src/cdp/utils/invocation-utils.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.ts
@@ -1,5 +1,6 @@
// NOTE: PostIngestionEvent is our context event - it should never be sent directly to an output, but rather transformed into a lightweight schema
import { DateTime } from 'luxon'
+import { Counter } from 'prom-client'
import { UUIDT } from '~/common/utils/utils'
@@ -17,6 +18,13 @@ import {
import { HogFunctionType } from '../types'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from './hog-function-filtering'
+/** The inputs step of the dead-letter pipeline. Read next to cdp_hog_function_filter_error. */
+const hogFunctionInputsErrors = new Counter({
+ name: 'cdp_hog_function_inputs_error',
+ help: 'Building the inputs for an invocation threw, so no invocation was created',
+ labelNames: ['type'],
+})
+
export function createInvocation(
globals: HogFunctionInvocationGlobalsWithInputs,
hogFunction: HogFunctionType
@@ -106,6 +114,8 @@ export async function buildHogFunctionInvocations(
message: `Error building inputs for event ${triggerGlobals.event.uuid}: ${error.message}`,
})
+ hogFunctionInputsErrors.inc({ type: hogFunction.type })
+
metrics.push({
team_id: hogFunction.team_id,
app_source_id: hogFunction.id,