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): classify filter and input errors by who has to act (#105251)

Meikel Ratz9480485e439e
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 66e927d08202..72d9c9c6e1ec 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -136,6 +136,7 @@
"services/mcp/worker-configuration.d.ts",
"frontend/src/taxonomy/core-filter-definitions-by-group.json",
"services/mcp/src/lib/trace-property-allowlist.generated.ts",
+ "posthog/cdp/filter_globals.json",
"frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts",
"products/review_hog/backend/reviewer/prompts/**/schema.json",
"**/chart/*/templates/**",
diff --git a/common/hogvm/typescript/src/__tests__/execute.test.ts b/common/hogvm/typescript/src/__tests__/execute.test.ts
index 2d3e13ee4efe..6ee9a251fd4a 100644
--- a/common/hogvm/typescript/src/__tests__/execute.test.ts
+++ b/common/hogvm/typescript/src/__tests__/execute.test.ts
@@ -3,7 +3,7 @@ import RE2 from 're2'
import { exec, execAsync, execSync } from '../execute'
import { Operation as op } from '../operation'
import { BytecodeEntry } from '../types'
-import { UncaughtHogVMException } from '../utils'
+import { HogVMException, UncaughtHogVMException } from '../utils'
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
@@ -18,6 +18,71 @@ const tuple = (array: any[]): any[] => {
}
describe('hogvm execute', () => {
+ describe('error kinds', () => {
+ // The CDP decides what to do with a failed filter from this field, so each throw site has
+ // to say whether the bytecode did not fit the runtime, the data did not fit the code, or a
+ // limit was hit. Message text is not part of the contract.
+ const kindOf = (bytecode: any[], options = {}): string => {
+ try {
+ execSync(bytecode, options)
+ } catch (error) {
+ expect(error).toBeInstanceOf(HogVMException)
+ return error.kind
+ }
+ throw new Error('expected the program to throw')
+ }
+
+ test('contract: the bytecode asks for something the runtime does not have', () => {
+ // A filter reading a query-only field, saved before the compiler checked globals.
+ expect(kindOf(['_H', 1, op.STRING, '$virt_is_bot', op.GET_GLOBAL, 1])).toBe('contract')
+ // A ClickHouse aggregate that never existed in Hog.
+ expect(kindOf(['_H', 1, op.INTEGER, 1, op.CALL_GLOBAL, 'countDistinctIf', 1])).toBe('contract')
+ // Two-argument dateAdd, valid HogQL, three arguments in the VM.
+ expect(kindOf(['_H', 1, op.INTEGER, 1, op.INTEGER, 1, op.CALL_GLOBAL, 'dateAdd', 2])).toBe('contract')
+ // An opcode this VM does not know.
+ expect(kindOf(['_H', 1, 999])).toBe('contract')
+ // A host that gave the VM no regex engine. The same program fails on every event, unlike a
+ // pattern the engine rejects.
+ expect(kindOf(['_H', 1, op.STRING, 'a', op.STRING, 'b', op.CALL_GLOBAL, 'match', 2])).toBe('contract')
+ // A host that gave the VM no crypto module: the same, a capability the runtime lacks.
+ expect(kindOf(['_H', 1, op.STRING, 'a', op.CALL_GLOBAL, 'sha256Hex', 1])).toBe('contract')
+ })
+
+ test('data: the code ran and the value did not fit it', () => {
+ // A standard-library function refusing its argument.
+ expect(
+ kindOf(['_H', 1, op.STRING, 'bogus', op.INTEGER, 1, op.INTEGER, 1, op.CALL_GLOBAL, 'dateDiff', 3])
+ ).toBe('data')
+ // `throw Error('boom')` in user code.
+ expect(kindOf(['_H', 1, op.STRING, 'boom', op.CALL_GLOBAL, 'Error', 1, op.THROW])).toBe('data')
+ // A number where the library expects a string: the engine's TypeError depends on the event.
+ expect(kindOf(['_H', 1, op.STRING, ',', op.INTEGER, 42, op.CALL_GLOBAL, 'splitByString', 2])).toBe('data')
+ // `'admin' in properties.roles` on an event without roles: `in` meets null.
+ expect(kindOf(['_H', 1, op.NULL, op.STRING, 'admin', op.IN])).toBe('data')
+ // An index of 0 that came from a value, so the compiler could not refuse it.
+ expect(kindOf(['_H', 1, op.STRING, 'a', op.ARRAY, 1, op.INTEGER, 0, op.GET_PROPERTY])).toBe('data')
+ })
+
+ test('limit: the program hit a resource ceiling', () => {
+ expect(kindOf(['_H', 1, op.STRING, 'a string that is longer than the limit'], { memoryLimit: 8 })).toBe(
+ 'limit'
+ )
+ })
+
+ test('a raw JavaScript error from the standard library is a data error with its cause attached', () => {
+ // dateDiff throws a plain Error for its unit; the VM wraps it so the caller sees a Hog error.
+ let thrown: any
+ try {
+ execSync(['_H', 1, op.STRING, 'bogus', op.INTEGER, 1, op.INTEGER, 1, op.CALL_GLOBAL, 'dateDiff', 3])
+ } catch (error) {
+ thrown = error
+ }
+ expect(thrown).toBeInstanceOf(HogVMException)
+ expect(thrown.message).toContain('Unsupported unit for dateDiff')
+ expect(thrown.cause).toBeInstanceOf(Error)
+ })
+ })
+
test('execution results', async () => {
const globals = { properties: { foo: 'bar', nullValue: null } }
const options = {
diff --git a/common/hogvm/typescript/src/execute.ts b/common/hogvm/typescript/src/execute.ts
index 051a20302a7f..648d2b6ce388 100644
--- a/common/hogvm/typescript/src/execute.ts
+++ b/common/hogvm/typescript/src/execute.ts
@@ -34,6 +34,46 @@ import {
const ORDERING_OPERATIONS = new Set([Operation.GT, Operation.GT_EQ, Operation.LT, Operation.LT_EQ])
+/**
+ * The standard library reports a bad argument with a plain Error, or lets the engine throw a
+ * TypeError when a value of the wrong type meets a method call. Both depend on the event, so both
+ * become Hog data errors. A ReferenceError can only come from the library's own code and stays
+ * what it is. Checked by name, because an error from a native module or another realm fails
+ * instanceof against this realm's Error.
+ */
+function asDataError(error: unknown): unknown {
+ if (error instanceof HogVMException || typeof error !== 'object' || error === null) {
+ return error
+ }
+ const { name, message } = error as { name?: unknown; message?: unknown }
+ if (typeof message !== 'string' || name === 'ReferenceError') {
+ return error
+ }
+ return new HogVMException(message, 'data', { cause: error })
+}
+
+function callStl(
+ fn: (args: any[], name: string, options?: ExecOptions) => any,
+ args: any[],
+ name: string,
+ options?: ExecOptions
+): any {
+ try {
+ return fn(args, name, options)
+ } catch (error) {
+ throw asDataError(error)
+ }
+}
+
+/** For an operator whose failure depends on the values it met, such as `in` on a non-container. */
+function onValues<T>(fn: () => T): T {
+ try {
+ return fn()
+ } catch (error) {
+ throw asDataError(error)
+ }
+}
+
function compareValues(left: any, right: any, operation: Operation): boolean {
// SQL semantics: a null on either side of an ordering comparison is no match. Without this the
// native operator reads null as 0, so `length(missing) < 3` would match.
@@ -87,7 +127,7 @@ function compareValues(left: any, right: any, operation: Operation): boolean {
case Operation.LT_EQ:
return left <= right
default:
- throw new HogVMException(`Invalid comparison operation: ${operation}`)
+ throw new HogVMException(`Invalid comparison operation: ${operation}`, 'contract')
}
}
@@ -99,7 +139,7 @@ export function execSync(bytecode: any[] | VMState | Bytecodes, options?: ExecOp
if (response.error) {
throw response.error
}
- throw new HogVMException('Unexpected async function call: ' + response.asyncFunctionName)
+ throw new HogVMException('Unexpected async function call: ' + response.asyncFunctionName, 'contract')
}
export async function execAsync(bytecode: any[] | VMState | Bytecodes, options?: ExecOptions): Promise<ExecResult> {
@@ -128,10 +168,10 @@ export async function execAsync(bytecode: any[] | VMState | Bytecodes, options?:
)
vmState.stack.push(result)
} else {
- throw new HogVMException('Invalid async function call: ' + response.asyncFunctionName)
+ throw new HogVMException('Invalid async function call: ' + response.asyncFunctionName, 'contract')
}
} else {
- throw new HogVMException('Invalid async function call')
+ throw new HogVMException('Invalid async function call', 'contract')
}
}
}
@@ -153,7 +193,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
}
const rootBytecode = bytecodes.root.bytecode
if (!rootBytecode || rootBytecode.length === 0 || (rootBytecode[0] !== '_h' && rootBytecode[0] !== '_H')) {
- throw new HogVMException("Invalid HogQL bytecode, must start with '_H'")
+ throw new HogVMException("Invalid HogQL bytecode, must start with '_H'", 'contract')
}
const version = rootBytecode[0] === '_H' ? (rootBytecode[1] ?? 0) : 0
@@ -231,10 +271,10 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
chunkBytecode = chunk.bytecode
chunkGlobals = chunk.globals ?? {}
} else {
- throw new HogVMException(`Unknown chunk: ${frame.chunk}`)
+ throw new HogVMException(`Unknown chunk: ${frame.chunk}`, 'contract')
}
} else {
- throw new HogVMException(`Unknown chunk: ${frame.chunk}`)
+ throw new HogVMException(`Unknown chunk: ${frame.chunk}`, 'contract')
}
if (frame.ip === 0 && (chunkBytecode[0] === '_H' || chunkBytecode[0] === '_h')) {
// TODO: store chunkVersion
@@ -246,7 +286,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
function popStack(): any {
if (stack.length === 0) {
logTelemetry()
- throw new HogVMException('Invalid HogQL bytecode, stack is empty, can not pop')
+ throw new HogVMException('Invalid HogQL bytecode, stack is empty, can not pop', 'contract')
}
memUsed -= memStack.pop() ?? 0
return stack.pop()
@@ -257,7 +297,10 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
memUsed += memStack[memStack.length - 1]
maxMemUsed = Math.max(maxMemUsed, memUsed)
if (memUsed > memLimit && memLimit > 0) {
- throw new HogVMException(`Memory limit of ${memLimit} bytes exceeded. Tried to allocate ${memUsed} bytes.`)
+ throw new HogVMException(
+ `Memory limit of ${memLimit} bytes exceeded. Tried to allocate ${memUsed} bytes.`,
+ 'limit'
+ )
}
return stack.push(value)
}
@@ -269,7 +312,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
function stackKeepFirstElements(count: number): any[] {
if (count < 0 || stack.length < count) {
- throw new HogVMException('Stack underflow')
+ throw new HogVMException('Stack underflow', 'contract')
}
for (let i = sortedUpValues.length - 1; i >= 0; i--) {
if (sortedUpValues[i].location >= count) {
@@ -288,14 +331,17 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
function next(): any {
if (frame.ip >= chunkBytecode.length - 1) {
- throw new HogVMException('Unexpected end of bytecode')
+ throw new HogVMException('Unexpected end of bytecode', 'contract')
}
return chunkBytecode[++frame.ip]
}
function checkTimeout(): void {
if (syncDuration + Date.now() - startTime > timeout) {
- throw new HogVMException(`Execution timed out after ${timeout / 1000} seconds. Performed ${ops} ops.`)
+ throw new HogVMException(
+ `Execution timed out after ${timeout / 1000} seconds. Performed ${ops} ops.`,
+ 'limit'
+ )
}
}
@@ -342,10 +388,19 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
function regexMatch(): (regex: string, value: string) => boolean {
if (!options?.external?.regex?.match) {
- throw new HogVMException('Set options.external.regex.match for RegEx support')
+ throw new HogVMException('Set options.external.regex.match for RegEx support', 'contract')
+ }
+ return (regex: string, value: string): boolean => {
+ if (!regex || !value) {
+ return false
+ }
+ try {
+ return !!options.external?.regex?.match(regex, value)
+ } catch (error) {
+ // The pattern is a value the program supplied, so a pattern the engine refuses is a data error.
+ throw asDataError(error)
+ }
}
- return (regex: string, value: string): boolean =>
- regex && value ? !!options.external?.regex?.match(regex, value) : false
}
const logTelemetry = (): void => {
@@ -486,24 +541,24 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
pushStack(compareValues(popStack(), popStack(), Operation.LT_EQ))
break
case Operation.LIKE:
- pushStack(like(popStack(), popStack(), false, options?.external?.regex?.match))
+ pushStack(onValues(() => like(popStack(), popStack(), false, options?.external?.regex?.match)))
break
case Operation.ILIKE:
- pushStack(like(popStack(), popStack(), true, options?.external?.regex?.match))
+ pushStack(onValues(() => like(popStack(), popStack(), true, options?.external?.regex?.match)))
break
case Operation.NOT_LIKE:
- pushStack(!like(popStack(), popStack(), false, options?.external?.regex?.match))
+ pushStack(!onValues(() => like(popStack(), popStack(), false, options?.external?.regex?.match)))
break
case Operation.NOT_ILIKE:
- pushStack(!like(popStack(), popStack(), true, options?.external?.regex?.match))
+ pushStack(!onValues(() => like(popStack(), popStack(), true, options?.external?.regex?.match)))
break
case Operation.IN:
temp = popStack()
- pushStack(popStack().includes(temp))
+ pushStack(onValues(() => popStack().includes(temp)))
break
case Operation.NOT_IN:
temp = popStack()
- pushStack(!popStack().includes(temp))
+ pushStack(!onValues(() => popStack().includes(temp)))
break
case Operation.REGEX:
temp = popStack()
@@ -583,7 +638,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
)
)
} else {
- throw new HogVMException(`Global variable not found: ${chain.join('.')}`)
+ throw new HogVMException(`Global variable not found: ${chain.join('.')}`, 'contract')
}
break
}
@@ -624,16 +679,16 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
break
case Operation.GET_PROPERTY:
temp = popStack() // property
- pushStack(getNestedValue(popStack(), [temp]))
+ pushStack(onValues(() => getNestedValue(popStack(), [temp])))
break
case Operation.GET_PROPERTY_NULLISH:
temp = popStack() // property
- pushStack(getNestedValue(popStack(), [temp], true))
+ pushStack(onValues(() => getNestedValue(popStack(), [temp], true)))
break
case Operation.SET_PROPERTY:
temp = popStack() // value
temp2 = popStack() // field
- setNestedValue(popStack(), [temp2], temp)
+ onValues(() => setNestedValue(popStack(), [temp2], temp))
break
case Operation.DICT:
temp = next() * 2 // number of elements to remove from the stack
@@ -699,13 +754,14 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
case Operation.CLOSURE: {
const callable = popStack()
if (!isHogCallable(callable)) {
- throw new HogVMException(`Invalid callable: ${JSON.stringify(callable)}`)
+ throw new HogVMException(`Invalid callable: ${JSON.stringify(callable)}`, 'contract')
}
const upvalueCount = next()
const closureUpValues: number[] = []
if (upvalueCount !== callable.upvalueCount) {
throw new HogVMException(
- `Invalid upvalue count. Expected ${callable.upvalueCount}, got ${upvalueCount}`
+ `Invalid upvalue count. Expected ${callable.upvalueCount}, got ${upvalueCount}`,
+ 'contract'
)
}
const stackStart = frame.stackStart
@@ -723,11 +779,11 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
case Operation.GET_UPVALUE: {
const index = next()
if (index >= frame.closure.upvalues.length) {
- throw new HogVMException(`Invalid upvalue index: ${index}`)
+ throw new HogVMException(`Invalid upvalue index: ${index}`, 'contract')
}
const upvalue = upvaluesById[frame.closure.upvalues[index]]
if (!isHogUpValue(upvalue)) {
- throw new HogVMException(`Invalid upvalue: ${upvalue}`)
+ throw new HogVMException(`Invalid upvalue: ${upvalue}`, 'contract')
}
if (upvalue.closed) {
pushStack(upvalue.value)
@@ -739,11 +795,11 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
case Operation.SET_UPVALUE: {
const index = next()
if (index >= frame.closure.upvalues.length) {
- throw new HogVMException(`Invalid upvalue index: ${index}`)
+ throw new HogVMException(`Invalid upvalue index: ${index}`, 'contract')
}
const upvalue = upvaluesById[frame.closure.upvalues[index]]
if (!isHogUpValue(upvalue)) {
- throw new HogVMException(`Invalid upvalue: ${upvalue}`)
+ throw new HogVMException(`Invalid upvalue: ${upvalue}`, 'contract')
}
if (upvalue.closed) {
upvalue.value = popStack()
@@ -785,10 +841,10 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
continue // resume the loop without incrementing frame.ip
} else {
if (temp > stack.length) {
- throw new HogVMException('Not enough arguments on the stack')
+ throw new HogVMException('Not enough arguments on the stack', 'contract')
}
if (temp > MAX_FUNCTION_ARGS_LENGTH) {
- throw new HogVMException('Too many arguments')
+ throw new HogVMException('Too many arguments', 'contract')
}
if (name === 'import') {
@@ -799,7 +855,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
.map(() => popStack())
: stackKeepFirstElements(stack.length - temp)
if (args.length !== 1) {
- throw new HogVMException(`Function ${name} requires exactly 1 argument`)
+ throw new HogVMException(`Function ${name} requires exactly 1 argument`, 'contract')
}
frame.ip += 1 // advance for when we return
frame = {
@@ -840,7 +896,10 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
Object.hasOwn(ASYNC_STL, name))
) {
if (asyncSteps >= maxAsyncSteps) {
- throw new HogVMException(`Exceeded maximum number of async steps: ${maxAsyncSteps}`)
+ throw new HogVMException(
+ `Exceeded maximum number of async steps: ${maxAsyncSteps}`,
+ 'limit'
+ )
}
const args =
@@ -866,11 +925,15 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
const stlFn = STL[name]
if (stlFn.minArgs !== undefined && temp < stlFn.minArgs) {
throw new HogVMException(
- `Function ${name} requires at least ${stlFn.minArgs} arguments`
+ `Function ${name} requires at least ${stlFn.minArgs} arguments`,
+ 'contract'
)
}
if (stlFn.maxArgs !== undefined && temp > stlFn.maxArgs) {
- throw new HogVMException(`Function ${name} requires at most ${stlFn.maxArgs} arguments`)
+ throw new HogVMException(
+ `Function ${name} requires at most ${stlFn.maxArgs} arguments`,
+ 'contract'
+ )
}
const args =
version === 0
@@ -878,12 +941,13 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
.fill(null)
.map(() => popStack())
: stackKeepFirstElements(stack.length - temp)
- pushStack(stlFn.fn(args, name, options))
+ pushStack(callStl(stlFn.fn, args, name, options))
} else if (Object.hasOwn(BYTECODE_STL, name)) {
const argNames = BYTECODE_STL[name][0]
if (argNames.length !== temp) {
throw new HogVMException(
- `Function ${name} requires exactly ${argNames.length} arguments`
+ `Function ${name} requires exactly ${argNames.length} arguments`,
+ 'contract'
)
}
frame.ip += 1 // advance for when we return
@@ -905,11 +969,14 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
setChunkBytecode()
callStack.push(frame)
if (callStack.length > CALLSTACK_LENGTH) {
- throw new HogVMException(`Call stack exceeded maximum length of ${CALLSTACK_LENGTH}`)
+ throw new HogVMException(
+ `Call stack exceeded maximum length of ${CALLSTACK_LENGTH}`,
+ 'limit'
+ )
}
continue // resume the loop without incrementing frame.ip
} else {
- throw new HogVMException(`Unsupported function call: ${name}`)
+ throw new HogVMException(`Unsupported function call: ${name}`, 'contract')
}
}
break
@@ -918,17 +985,17 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
checkTimeout()
const closure = popStack()
if (!isHogClosure(closure)) {
- throw new HogVMException(`Invalid closure: ${JSON.stringify(closure)}`)
+ throw new HogVMException(`Invalid closure: ${JSON.stringify(closure)}`, 'contract')
}
if (!isHogCallable(closure.callable)) {
- throw new HogVMException(`Invalid callable: ${JSON.stringify(closure.callable)}`)
+ throw new HogVMException(`Invalid callable: ${JSON.stringify(closure.callable)}`, 'contract')
}
temp = next() // args.length
if (temp > stack.length) {
- throw new HogVMException('Not enough arguments on the stack')
+ throw new HogVMException('Not enough arguments on the stack', 'contract')
}
if (temp > MAX_FUNCTION_ARGS_LENGTH) {
- throw new HogVMException('Too many arguments')
+ throw new HogVMException('Too many arguments', 'contract')
}
if (closure.callable.__hogCallable__ === 'local') {
if (closure.callable.argCount > temp) {
@@ -937,7 +1004,8 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
}
} else if (closure.callable.argCount < temp) {
throw new HogVMException(
- `Too many arguments. Passed ${temp}, expected ${closure.callable.argCount}`
+ `Too many arguments. Passed ${temp}, expected ${closure.callable.argCount}`,
+ 'contract'
)
}
frame.ip += 1 // advance for when we return
@@ -951,22 +1019,27 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
setChunkBytecode()
callStack.push(frame)
if (callStack.length > CALLSTACK_LENGTH) {
- throw new HogVMException(`Call stack exceeded maximum length of ${CALLSTACK_LENGTH}`)
+ throw new HogVMException(
+ `Call stack exceeded maximum length of ${CALLSTACK_LENGTH}`,
+ 'limit'
+ )
}
continue // resume the loop without incrementing frame.ip
} else if (closure.callable.__hogCallable__ === 'stl') {
if (!closure.callable.name || !Object.hasOwn(STL, closure.callable.name)) {
- throw new HogVMException(`Unsupported function call: ${closure.callable.name}`)
+ throw new HogVMException(`Unsupported function call: ${closure.callable.name}`, 'contract')
}
const stlFn = STL[closure.callable.name]
if (stlFn.minArgs !== undefined && temp < stlFn.minArgs) {
throw new HogVMException(
- `Function ${closure.callable.name} requires at least ${stlFn.minArgs} arguments`
+ `Function ${closure.callable.name} requires at least ${stlFn.minArgs} arguments`,
+ 'contract'
)
}
if (stlFn.maxArgs !== undefined && temp > stlFn.maxArgs) {
throw new HogVMException(
- `Function ${closure.callable.name} requires at most ${stlFn.maxArgs} arguments`
+ `Function ${closure.callable.name} requires at most ${stlFn.maxArgs} arguments`,
+ 'contract'
)
}
const args = Array(temp)
@@ -980,10 +1053,13 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
args.push(null)
}
}
- pushStack(stlFn.fn(args, closure.callable.name, options))
+ pushStack(callStl(stlFn.fn, args, closure.callable.name, options))
} else if (closure.callable.__hogCallable__ === 'async') {
if (asyncSteps >= maxAsyncSteps) {
- throw new HogVMException(`Exceeded maximum number of async steps: ${maxAsyncSteps}`)
+ throw new HogVMException(
+ `Exceeded maximum number of async steps: ${maxAsyncSteps}`,
+ 'limit'
+ )
}
const args = Array(temp)
.fill(null)
@@ -993,10 +1069,13 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
finished: false,
asyncFunctionName: closure.callable.name,
asyncFunctionArgs: args.map((v) => convertHogToJS(v)),
- state: { ...getVMState(), asyncSteps: asyncSteps + 1 },
+ state: {
+ ...getVMState(),
+ asyncSteps: asyncSteps + 1,
+ },
} satisfies ExecResult
} else {
- throw new HogVMException(`Unsupported function call: ${closure.callable.name}`)
+ throw new HogVMException(`Unsupported function call: ${closure.callable.name}`, 'contract')
}
break
}
@@ -1011,7 +1090,7 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
if (throwStack.length > 0) {
throwStack.pop()
} else {
- throw new HogVMException('Invalid operation POP_TRY: no try block to pop')
+ throw new HogVMException('Invalid operation POP_TRY: no try block to pop', 'contract')
}
break
case Operation.THROW: {
@@ -1035,7 +1114,8 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
}
default:
throw new HogVMException(
- `Unexpected node while running bytecode in chunk "${frame.chunk}": ${chunkBytecode[frame.ip]}`
+ `Unexpected node while running bytecode in chunk "${frame.chunk}": ${chunkBytecode[frame.ip]}`,
+ 'contract'
)
}
@@ -1043,6 +1123,11 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
frame.ip++
}
} catch (e) {
- return { result: null, finished: false, error: e, state: getVMState() } satisfies ExecResult
+ return {
+ result: null,
+ finished: false,
+ error: e,
+ state: getVMState(),
+ } satisfies ExecResult
}
}
diff --git a/common/hogvm/typescript/src/stl/crypto.ts b/common/hogvm/typescript/src/stl/crypto.ts
index d20d956fc2f3..150d0e11e48f 100644
--- a/common/hogvm/typescript/src/stl/crypto.ts
+++ b/common/hogvm/typescript/src/stl/crypto.ts
@@ -1,4 +1,5 @@
import { ExecOptions } from '../types'
+import { HogVMException } from '../utils'
export function sha256(
data: string | null,
@@ -10,7 +11,7 @@ export function sha256(
}
const crypto = options?.external?.crypto
if (!crypto) {
- throw new Error('The crypto module is required for "sha256Hex" to work.')
+ throw new HogVMException('The crypto module is required for "sha256Hex" to work.', 'contract')
}
return crypto.createHash('sha256').update(data).digest(encoding)
}
@@ -25,7 +26,7 @@ export function md5(
}
const crypto = options?.external?.crypto
if (!crypto) {
- throw new Error('The crypto module is required for "md5Hex" to work.')
+ throw new HogVMException('The crypto module is required for "md5Hex" to work.', 'contract')
}
return crypto.createHash('md5').update(data).digest(encoding)
}
@@ -41,7 +42,7 @@ export function sha1(
}
const crypto = options?.external?.crypto
if (!crypto) {
- throw new Error('The crypto module is required for "sha1Hex" to work.')
+ throw new HogVMException('The crypto module is required for "sha1Hex" to work.', 'contract')
}
return crypto.createHash('sha1').update(data).digest(encoding)
}
@@ -55,7 +56,7 @@ function hmacChain(
): string {
const crypto = options?.external?.crypto
if (!crypto) {
- throw new Error(`The crypto module is required for "${name}" to work.`)
+ throw new HogVMException(`The crypto module is required for "${name}" to work.`, 'contract')
}
if (data.length < 2) {
throw new Error('Data array must contain at least two elements.')
diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.ts
index bbf31b67d30e..3dfba60a37a4 100644
--- a/common/hogvm/typescript/src/stl/stl.ts
+++ b/common/hogvm/typescript/src/stl/stl.ts
@@ -2,7 +2,7 @@ import { DateTime } from 'luxon'
import { isHogAST, isHogCallable, isHogClosure, isHogDate, isHogDateTime, isHogError, newHogError } from '../objects'
import { AsyncSTLFunction, HogDate, HogDateTime, HogInterval, STLFunction } from '../types'
-import { getNestedValue, like } from '../utils'
+import { HogVMException, getNestedValue, like } from '../utils'
import { md5, sha1, sha1HmacChain, sha256, sha256HmacChain } from './crypto'
import {
formatDateTime,
@@ -505,7 +505,7 @@ export const STL: Record<string, STLFunction> = {
match: {
fn: (args, _name, options) => {
if (!options?.external?.regex?.match) {
- throw new Error('Set options.external.regex.match for RegEx support')
+ throw new HogVMException('Set options.external.regex.match for RegEx support', 'contract')
}
return !args[0] || !args[1] ? false : options.external.regex.match(args[1], args[0])
},
@@ -517,7 +517,7 @@ export const STL: Record<string, STLFunction> = {
extractRegex: {
fn: (args, _name, options) => {
if (!options?.external?.regex?.extract) {
- throw new Error('Set options.external.regex.extract for RegEx extract support')
+ throw new HogVMException('Set options.external.regex.extract for RegEx extract support', 'contract')
}
if (args[0] == null || args[1] == null) {
return ''
diff --git a/common/hogvm/typescript/src/utils.ts b/common/hogvm/typescript/src/utils.ts
index 650c6d1bd3c5..b338fc11acaf 100644
--- a/common/hogvm/typescript/src/utils.ts
+++ b/common/hogvm/typescript/src/utils.ts
@@ -12,10 +12,22 @@ function temporalSeconds(value: any): number | null {
return null
}
+/**
+ * What a failure says about the program, so a caller can decide what to do with it without reading
+ * the message. `contract`: the bytecode asks for something this runtime does not have (a global, a
+ * function, an arity, an opcode), so the same program fails on every input until one of them changes.
+ * `data`: the program fits the runtime and a value did not fit the program, so another input may
+ * pass. `limit`: a resource ceiling was hit.
+ */
+export type HogVMErrorKind = 'contract' | 'data' | 'limit'
+
export class HogVMException extends Error {
- constructor(message: string) {
- super(message)
+ kind: HogVMErrorKind
+
+ constructor(message: string, kind: HogVMErrorKind = 'data', options?: { cause?: unknown }) {
+ super(message, options)
this.name = 'HogVMException'
+ this.kind = kind
}
}
@@ -24,7 +36,7 @@ export class UncaughtHogVMException extends HogVMException {
payload: any
constructor(type: string, message: string, payload: any = null) {
- super(message)
+ super(message, 'data')
this.name = 'UncaughtHogVMException'
this.type = type
this.payload = payload
diff --git a/nodejs/src/cdp/services/hog-inputs.service.test.ts b/nodejs/src/cdp/services/hog-inputs.service.test.ts
index eb70b1974f1d..263d7e1741ff 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.test.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.test.ts
@@ -1,6 +1,7 @@
import '~/tests/helpers/mocks/date.mock'
import { DateTime } from 'luxon'
+import { inspect } from 'util'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { createTestTeamFixture } from '~/tests/helpers/sql'
@@ -9,7 +10,7 @@ import { Hub, Team } from '~/types'
import { createHogExecutionGlobals, createHogFunction, insertIntegration } from '../_tests/fixtures'
import { compileHog } from '../templates/compiler'
import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'
-import { HogInputsService, formatHogInput, getAppIdentifierForPush } from './hog-inputs.service'
+import { HogInputsService, formatHogInput, formatLiquidInput, getAppIdentifierForPush } from './hog-inputs.service'
import { RecipientTokensService } from './messaging/recipient-tokens.service'
describe('getAppIdentifierForPush', () => {
@@ -131,9 +132,40 @@ describe('Hog Inputs', () => {
)
// dateDiff('bogus', 1, 1): the VM quotes its argument, which can be a secret input.
const quotesArgument = ['_H', 1, 32, 'bogus', 33, 1, 33, 1, 2, 'dateDiff', 3]
- await expect(formatHogInput(quotesArgument, globals, 'field')).rejects.toThrow(
- /^Could not execute bytecode for input field: field$/
+ const thrown = await formatHogInput(quotesArgument, globals, 'field').then(
+ () => undefined,
+ (error) => error
)
+ expect(thrown.message).toMatch(/^Could not execute bytecode for input field: field$/)
+ // The kind travels for the classifier; the quoted argument does not, even through a serialized cause chain.
+ expect(thrown.cause).toMatchObject({ kind: 'data' })
+ expect(inspect(thrown)).not.toContain('bogus')
+ })
+
+ it.each([
+ ['an unsupported filter', '{{ event.event | where_exp: "i", "i" }}', 'contract'],
+ ['a syntax error', '{% if %}', 'contract'],
+ // The same template renders for a well-formed URL, so this failure belongs to the event.
+ ['a malformed URL meeting url_decode', '{{ event.properties.url | url_decode }}', 'data'],
+ [
+ 'a template over its memory budget',
+ "{% assign s = 'aaaaaaaa' %}{% for i in (1..40) %}{% assign s = s | append: s %}{% endfor %}{{ s | size }}",
+ 'limit',
+ ],
+ ])('gives a liquid failure from %s a kind and keeps its message', (_name, template, kind) => {
+ const globals = createHogExecutionGlobals({
+ event: { event: '$pageview', properties: { url: '%' } } as any,
+ inputs: {},
+ } as any) as any
+ let thrown: any
+ try {
+ formatLiquidInput(template, globals, 'field')
+ } catch (error) {
+ thrown = error
+ }
+ expect(thrown).toBeInstanceOf(Error)
+ expect(thrown.message).toBe(thrown.cause.message)
+ expect(thrown.cause).toMatchObject({ kind })
})
it('can handle deep null and undefined values', async () => {
diff --git a/nodejs/src/cdp/services/hog-inputs.service.ts b/nodejs/src/cdp/services/hog-inputs.service.ts
index 7abeb44e3b82..ba17ee56bc82 100644
--- a/nodejs/src/cdp/services/hog-inputs.service.ts
+++ b/nodejs/src/cdp/services/hog-inputs.service.ts
@@ -1,4 +1,4 @@
-import { convertHogToJS } from '@posthog/hogvm'
+import { HogVMErrorKind, HogVMException, convertHogToJS } from '@posthog/hogvm'
import { CyclotronInputType } from '~/cdp/schema/cyclotron'
import { ACCESS_TOKEN_PLACEHOLDER } from '~/common/config/constants'
@@ -6,6 +6,7 @@ import { logger } from '~/common/utils/logger'
import { HogFunctionInvocationGlobals, HogFunctionInvocationGlobalsWithInputs, HogFunctionType } from '../types'
import { EncryptedFields } from '../utils/encryption-utils'
+import { isHogVMErrorKind } from '../utils/hog-error-classification'
import { execHog } from '../utils/hog-exec'
import { LiquidRenderBudget, LiquidRenderer } from '../utils/liquid'
import { getDevicePushSubscriptionToken } from '../utils/push-subscription-utils'
@@ -263,8 +264,14 @@ export const formatHogInput = async (
// An uncaught hog exception comes back as an unfinished run with the error attached.
// Other VM messages can echo an argument, and an argument can be a secret input.
const message: string = result?.error?.message ?? ''
- const cause = message.startsWith('Global variable not found') ? `: ${message}` : ''
- throw new Error(`Could not execute bytecode for input field: ${key}${cause}`)
+ const detail = message.startsWith('Global variable not found') ? `: ${message}` : ''
+ // Only the kind travels, so the caller can classify the failure. The VM error itself stays
+ // behind: a serialized cause chain would print its message, and that can hold a secret.
+ const kind: unknown = result?.error?.kind
+ const cause = isHogVMErrorKind(kind)
+ ? new HogVMException(`Input field ${key} could not be evaluated`, kind)
+ : undefined
+ throw new Error(`Could not execute bytecode for input field: ${key}${detail}`, { cause })
}
return convertHogToJS(result.result)
}
@@ -298,6 +305,21 @@ export const formatHogInput = async (
return bytecode
}
+/**
+ * A parse error or a refused filter fails the template on every event. Any other render error is
+ * the template meeting this event's values, so another event may pass. A budget is a limit.
+ */
+const liquidErrorKind = (error: unknown): HogVMErrorKind => {
+ const { name, message } = error instanceof Error ? error : { name: '', message: String(error) }
+ if (message.includes('limit exceeded')) {
+ return 'limit'
+ }
+ if (name === 'RenderError' && !message.includes('is not supported')) {
+ return 'data'
+ }
+ return 'contract'
+}
+
export const formatLiquidInput = (
value: unknown,
globals: HogFunctionInvocationGlobalsWithInputs,
@@ -309,7 +331,13 @@ export const formatLiquidInput = (
}
if (typeof value === 'string') {
- return LiquidRenderer.renderWithHogFunctionGlobals(value, globals, budget)
+ try {
+ return LiquidRenderer.renderWithHogFunctionGlobals(value, globals, budget)
+ } catch (error) {
+ // The renderer's message names the template line the owner has to fix, so it stays as is.
+ const message = error instanceof Error ? error.message : String(error)
+ throw new Error(message, { cause: new HogVMException(message, liquidErrorKind(error)) })
+ }
}
if (Array.isArray(value)) {
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 3e9b6e1587a3..1954d850ee9a 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -60,6 +60,11 @@ export interface HogFunctionFilters {
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
+ /**
+ * The runtime contract hash the bytecode was compiled against, from filter_globals.json. Absent on
+ * bytecode saved before the compiler checked globals and functions.
+ */
+ bytecode_contract?: string
}
export type GroupType = {
diff --git a/nodejs/src/cdp/utils/filter-runtime.test.ts b/nodejs/src/cdp/utils/filter-runtime.test.ts
index 16fa6fe7cc21..24ce3b3f08bf 100644
--- a/nodejs/src/cdp/utils/filter-runtime.test.ts
+++ b/nodejs/src/cdp/utils/filter-runtime.test.ts
@@ -3,27 +3,53 @@ import { join } from 'path'
import { parseJSON } from '~/common/utils/json-parse'
-import { FILTER_GLOBALS_RELATIVE_PATH, describeFilterRuntime, renderFilterGlobalsFile } from './filter-runtime'
+import {
+ FILTER_GLOBALS_RELATIVE_PATH,
+ FilterRuntime,
+ describeFilterRuntime,
+ renderFilterGlobalsFile,
+ runtimeContractHash,
+} from './filter-runtime'
import { execHog } from './hog-exec'
describe('filter-runtime', () => {
const committed = (): string => readFileSync(join(__dirname, '../../../..', FILTER_GLOBALS_RELATIVE_PATH), 'utf8')
- it('matches the committed file Django reads', () => {
+ it('matches the committed file Django reads, byte for byte', () => {
// The one gate. A global or a standard-library function added to the runtime lands here as a
// diff until the file is regenerated, so Django cannot silently validate against a stale set.
- // Compared as parsed JSON: the pre-commit hook reformats the file, and whitespace is not the
- // contract.
- const expected = parseJSON(renderFilterGlobalsFile(describeFilterRuntime()))
- const actual = parseJSON(committed())
- if (JSON.stringify(actual) !== JSON.stringify(expected)) {
- // toEqual alone prints a diff and nothing else; say what to do about it.
+ // Compared as text: the generator is the only writer of this file, and a reformat by hand or by
+ // a tool would show up here as churn on every later regenerate.
+ const expected = renderFilterGlobalsFile(describeFilterRuntime())
+ const actual = committed()
+ if (actual !== expected) {
throw new Error(
- `${FILTER_GLOBALS_RELATIVE_PATH} is stale. Run: pnpm --filter=@posthog/nodejs run build:filter-globals\n` +
- JSON.stringify({ expected, actual }, null, 2)
+ `${FILTER_GLOBALS_RELATIVE_PATH} differs from the generator's output. Run: pnpm --filter=@posthog/nodejs run build:filter-globals\n` +
+ JSON.stringify({ expected: parseJSON(expected), actual: parseJSON(actual) }, null, 2)
)
}
- expect(actual).toEqual(expected)
+ expect(actual).toBe(expected)
+ })
+
+ it('hashes the contract, not the file', () => {
+ // The hash is stamped on compiled bytecode and compared at run time, so it must move only when
+ // what the runtime provides moves: never on whitespace, key order or the comment in the file.
+ const runtime = describeFilterRuntime()
+ const hash = runtimeContractHash(runtime)
+ expect(hash).toMatch(/^[0-9a-f]{16}$/)
+ expect(parseJSON(committed()).contract).toBe(hash)
+
+ const reparsed = parseJSON(renderFilterGlobalsFile(runtime)) as FilterRuntime
+ expect(runtimeContractHash(reparsed)).toBe(hash)
+
+ const reordered: FilterRuntime = {
+ ...runtime,
+ functions: Object.fromEntries(Object.entries(runtime.functions).reverse()),
+ }
+ expect(runtimeContractHash(reordered)).toBe(hash)
+
+ const narrowed: FilterRuntime = { ...runtime, functions: { ...runtime.functions, lower: [1, 0] } }
+ expect(runtimeContractHash(narrowed)).not.toBe(hash)
})
it('describes what a hog function is actually evaluated with', () => {
diff --git a/nodejs/src/cdp/utils/filter-runtime.ts b/nodejs/src/cdp/utils/filter-runtime.ts
index 0365554a87d7..70b2ec5432d3 100644
--- a/nodejs/src/cdp/utils/filter-runtime.ts
+++ b/nodejs/src/cdp/utils/filter-runtime.ts
@@ -1,3 +1,5 @@
+import { createHash } from 'crypto'
+
import { ASYNC_STL, BYTECODE_STL, STL } from '@posthog/hogvm'
import { ClickHouseTimestamp, ProjectId, RawClickHouseEvent } from '../../types'
@@ -122,6 +124,29 @@ export function describeFilterRuntime(): FilterRuntime {
return { roots: fromInvocation, callables, functions, template_roots: Object.keys(templateRoots).sort() }
}
+/**
+ * One value that changes whenever the contract does. Django stamps it on the bytecode it compiles, so
+ * a filter that fails on a global or a function can be told apart from one compiled against an older
+ * runtime.
+ */
+export function runtimeContractHash(runtime: FilterRuntime = describeFilterRuntime()): string {
+ const canonical = JSON.stringify({
+ roots: runtime.roots,
+ callables: runtime.callables,
+ functions: Object.fromEntries(Object.entries(runtime.functions).sort(([a], [b]) => a.localeCompare(b))),
+ template_roots: runtime.template_roots,
+ })
+ return createHash('sha256').update(canonical).digest('hex').slice(0, 16)
+}
+
+let cachedRuntimeContractHash: string | undefined
+
+/** The hash for this process. Computed on first use, because the description walks the whole standard library. */
+export function currentRuntimeContractHash(): string {
+ cachedRuntimeContractHash ??= runtimeContractHash()
+ return cachedRuntimeContractHash
+}
+
export function renderFilterGlobalsFile(runtime: FilterRuntime): string {
return (
JSON.stringify(
@@ -133,14 +158,16 @@ export function renderFilterGlobalsFile(runtime: FilterRuntime): string {
'ones a filter can pass as a callback. functions are every standard-library name a filter can ' +
'call directly, with the argument count the VM enforces as [min, max]. template_roots are the ' +
'names an input template can read. Django reads this to refuse a filter or an input the ' +
- 'runtime could not evaluate.',
+ 'runtime could not evaluate. contract is a hash of the rest, stamped on compiled bytecode.',
+ contract: runtimeContractHash(runtime),
roots: runtime.roots,
callables: runtime.callables,
functions: runtime.functions,
template_roots: runtime.template_roots,
},
null,
- // Matches what the pre-commit hook (bin/hogli format:yaml) writes, so a regenerate is a no-op.
+ // The pre-commit formatter is kept off this file by an ignorePatterns entry in .oxfmtrc.json, so
+ // this output is byte-stable and the staleness test can compare the file as text.
4
) + '\n'
)
diff --git a/nodejs/src/cdp/utils/hog-error-classification.test.ts b/nodejs/src/cdp/utils/hog-error-classification.test.ts
new file mode 100644
index 000000000000..27f12f03d0d1
--- /dev/null
+++ b/nodejs/src/cdp/utils/hog-error-classification.test.ts
@@ -0,0 +1,100 @@
+import { HogVMException } from '@posthog/hogvm'
+
+import { compileHog } from '../templates/compiler'
+import { HogFunctionFilterGlobals } from '../types'
+import { runtimeContractHash } from './filter-runtime'
+import { classifyHogError } from './hog-error-classification'
+import { execHog } from './hog-exec'
+
+// Every filter in this file is one we have seen fail in production, written fresh.
+describe('classifyHogError', () => {
+ const runtime = runtimeContractHash()
+ const stale = 'contract-from-before-the-runtime-changed'
+
+ const failingFilter = async (hog: string, globals: Partial<HogFunctionFilterGlobals> = {}): Promise<unknown> => {
+ const bytecode = await compileHog(hog)
+ const { error, execResult } = await execHog(bytecode, {
+ globals: { event: '$pageview', properties: {}, ...globals },
+ })
+ const thrown = error ?? execResult?.error
+ expect(thrown).toBeDefined()
+ return thrown
+ }
+
+ describe('contract errors depend on what the filter was compiled against', () => {
+ it.each([
+ ['a query-only field', 'return $virt_is_bot = false'],
+ [
+ 'a two-argument dateAdd, valid in HogQL and not in the VM',
+ "return dateAdd(toIntervalDay(1), toDateTime('2026-01-01')) > now()",
+ ],
+ ])('%s', async (_name, hog) => {
+ const error = await failingFilter(hog)
+ // Saved before the compiler checked anything: the owner has to fix it, replay cannot.
+ expect(classifyHogError(error, { bytecodeContract: undefined, runtimeContract: runtime })).toBe('legacy')
+ // Compiled against an older runtime: we changed the contract, replay after the fix.
+ expect(classifyHogError(error, { bytecodeContract: stale, runtimeContract: runtime })).toBe('drift')
+ // Compiled against this runtime and still failing: the compiler and the VM disagree.
+ expect(classifyHogError(error, { bytecodeContract: runtime, runtimeContract: runtime })).toBe('bug')
+ })
+
+ it('an aggregate that does not exist in Hog', async () => {
+ const { error, execResult } = await execHog(['_H', 1, 33, 1, 2, 'countDistinctIf', 1], { globals: {} })
+ expect(classifyHogError(error ?? execResult?.error, { runtimeContract: runtime })).toBe('legacy')
+ })
+ })
+
+ describe('data errors are the same whatever the filter was compiled against', () => {
+ it.each<[string, string, Partial<HogFunctionFilterGlobals>]>([
+ ['a standard-library function refusing its argument', "return dateDiff('bogus', now(), now()) > 1", {}],
+ [
+ 'a property of the wrong type for a standard-library function',
+ "return length(splitByString(',', properties.tags)) > 1",
+ { properties: { tags: 42 } },
+ ],
+ [
+ 'an invalid regex written into the filter',
+ "return match(properties.url, '(')",
+ { properties: { url: 'x' } },
+ ],
+ ["a throw in the filter's own code", "throw Error('boom')", {}],
+ [
+ 'a membership test on a property the event does not have',
+ "return 'admin' in person.properties.roles",
+ { person: { id: 'p', properties: {} } },
+ ],
+ ])('%s', async (_name, hog, globals) => {
+ const error = await failingFilter(hog, globals)
+ for (const bytecodeContract of [undefined, stale, runtime]) {
+ expect(classifyHogError(error, { bytecodeContract, runtimeContract: runtime })).toBe('data')
+ }
+ })
+ })
+
+ it("a filter that runs out of time is the owner's loop, not ours", async () => {
+ // Replay would time out again, so this is never parked. Read alongside the fleet: many
+ // functions hitting it at once is a starved worker, one function is a bad program.
+ const bytecode = await compileHog('let i := 0; while (true) { i := i + 1 } return i')
+ const { error, execResult } = await execHog(bytecode, { globals: {}, timeout: 1 })
+ expect(classifyHogError(error ?? execResult?.error, { runtimeContract: runtime })).toBe('limit')
+ })
+
+ describe('platform errors are ours', () => {
+ it('a JavaScript error the VM let through', () => {
+ const error = new TypeError('Cannot convert undefined or null to object')
+ expect(classifyHogError(error, { runtimeContract: runtime })).toBe('platform')
+ })
+
+ it('anything that is not an error object', () => {
+ expect(classifyHogError('a string', { runtimeContract: runtime })).toBe('platform')
+ expect(classifyHogError(undefined, { runtimeContract: runtime })).toBe('platform')
+ })
+ })
+
+ it('follows the cause chain, so a wrapped input error keeps its class', () => {
+ const wrapped = new Error('Could not execute bytecode for input field: url', {
+ cause: new HogVMException('Global variable not found: distinct_id', 'contract'),
+ })
+ expect(classifyHogError(wrapped, { bytecodeContract: stale, runtimeContract: runtime })).toBe('drift')
+ })
+})
diff --git a/nodejs/src/cdp/utils/hog-error-classification.ts b/nodejs/src/cdp/utils/hog-error-classification.ts
new file mode 100644
index 000000000000..0cb7b737cad8
--- /dev/null
+++ b/nodejs/src/cdp/utils/hog-error-classification.ts
@@ -0,0 +1,70 @@
+import { HogVMErrorKind, HogVMException } from '@posthog/hogvm'
+
+/**
+ * Who has to act on a failed filter or input.
+ *
+ * - `data`: the program fits the runtime and this event did not fit the program. Another event may
+ * pass, so nothing is broken and nobody needs to act.
+ * - `legacy`: the program asks the runtime for something it does not have, and was saved before the
+ * compiler checked that. The owner has to fix the function; replaying the event cannot.
+ * - `drift`: the same, but the program was compiled against an older runtime, so a change on our side
+ * broke it. Replay after the runtime or the compiler is fixed.
+ * - `bug`: the same, but compiled against this runtime, so the compiler and the VM disagree about
+ * what exists. Ours to fix.
+ * - `limit`: the program ran out of time, memory or stack. Replay would run out again, so it is the
+ * owner's to fix. Many functions hitting it at once is a different story, and the label shows that.
+ * - `platform`: a JavaScript error the VM let through, or something that is not an error at all.
+ * Ours to look at.
+ */
+export type HogErrorClass = 'data' | 'legacy' | 'drift' | 'bug' | 'limit' | 'platform'
+
+export type HogErrorContract = {
+ /** The stamp on the bytecode that ran, from `filters.bytecode_contract`. Absent on older bytecode. */
+ bytecodeContract?: string
+ /** The stamp of the runtime that ran it, from `currentRuntimeContractHash()`. */
+ runtimeContract: string
+}
+
+type KindedError = { kind: HogVMErrorKind }
+
+const KINDS: ReadonlySet<string> = new Set<HogVMErrorKind>(['contract', 'data', 'limit'])
+
+export const isHogVMErrorKind = (value: unknown): value is HogVMErrorKind =>
+ typeof value === 'string' && KINDS.has(value)
+
+// By shape rather than instanceof: the error can come from another realm or an older build of the VM.
+const isHogVMException = (error: object): error is KindedError =>
+ error instanceof HogVMException || isHogVMErrorKind((error as Partial<KindedError>).kind)
+
+/**
+ * The first VM error in the cause chain. Callers wrap the VM's error to add the field or the
+ * function it happened in, and the wrapper carries no kind of its own.
+ */
+function findHogVMException(error: unknown): KindedError | undefined {
+ let current: unknown = error
+ for (let depth = 0; depth < 10 && typeof current === 'object' && current !== null; depth++) {
+ if (isHogVMException(current)) {
+ return current
+ }
+ current = (current as { cause?: unknown }).cause
+ }
+ return undefined
+}
+
+export function classifyHogError(error: unknown, contract: HogErrorContract): HogErrorClass {
+ const vmError = findHogVMException(error)
+ if (!vmError) {
+ return 'platform'
+ }
+ switch (vmError.kind) {
+ case 'data':
+ return 'data'
+ case 'limit':
+ return 'limit'
+ case 'contract':
+ if (!contract.bytecodeContract) {
+ return 'legacy'
+ }
+ return contract.bytecodeContract === contract.runtimeContract ? 'bug' : 'drift'
+ }
+}
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.test.ts b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
index 4ca60ed651b1..9ac2d1cad339 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.test.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
@@ -247,23 +247,27 @@ describe('hog-function-filtering', () => {
// 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
+ // Summed over the class label, which this table does not fix.
+ return (metric?.values ?? [])
+ .filter(
+ ({ labels }) =>
+ labels.reason === reason &&
+ labels.type === 'destination' &&
+ labels.caller === 'build_hog_function_invocations'
+ )
+ .reduce((sum, { value }) => sum + 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', {}],
+ ['not_compiled', { bytecode_error: 'Cohort membership cannot be evaluated' }, 'legacy'],
+ ['no_bytecode', {}, 'legacy'],
// 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) => {
+ ['vm_error', { bytecode: ['_H', 1, 999], filter_test_accounts: true }, 'legacy'],
+ // The same unknown opcode from a filter compiled against an older runtime is our change.
+ ['vm_error', { bytecode: ['_H', 1, 999], bytecode_contract: 'older', filter_test_accounts: true }, 'drift'],
+ ])('reports %s', async (reason, filters, errorClass) => {
const before = await errorCount(reason)
const result = await filterFunctionInstrumented({
@@ -279,8 +283,27 @@ describe('hog-function-filtering', () => {
})
expect(result.error).not.toBeUndefined()
+ expect(result.errorClass).toBe(errorClass)
expect(await errorCount(reason)).toBe(before + 1)
})
+
+ it('still skips the VM for a bytecode-only filter that carries a stamp', async () => {
+ // The bytecode is an unknown opcode, so running it would fail. A stamp alone is not a filter.
+ 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: { bytecode: ['_H', 1, 999], bytecode_contract: 'older' } as HogFunctionType['filters'],
+ filterGlobals: { event: '$pageview' } as HogFunctionFilterGlobals,
+ })
+
+ expect(result.error).toBeUndefined()
+ expect(result.match).toBe(true)
+ })
})
describe('Pre-filtering on event name', () => {
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.ts b/nodejs/src/cdp/utils/hog-function-filtering.ts
index c16a7f3b5b85..98f9cdb34d63 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.ts
@@ -17,6 +17,8 @@ import {
LogEntry,
MinimalAppMetric,
} from '../types'
+import { currentRuntimeContractHash } from './filter-runtime'
+import { HogErrorClass, classifyHogError } from './hog-error-classification'
import { execHog } from './hog-exec'
// Module-level constants for fixed regex patterns to avoid recompilation
@@ -58,7 +60,7 @@ 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', 'reason'],
+ labelNames: ['caller', 'type', 'reason', 'class'],
})
/**
@@ -77,6 +79,8 @@ const hogFunctionPreFilterCounter = new Counter({
interface HogFilterResult {
match: boolean
error?: unknown
+ /** Set beside `error`. Who has to act on it, see HogErrorClass. */
+ errorClass?: HogErrorClass
logs: LogEntry[]
metrics: MinimalAppMetric[]
}
@@ -416,7 +420,9 @@ export async function filterFunctionInstrumented(options: {
try {
// If there are no filters (only bytecode exists then on the filter object)
// everything matches no need to execute bytecode (lets save those cpu cycles)
- if (filters && Object.keys(filters).length === 1 && 'bytecode' in filters) {
+ // The stamp is metadata about the bytecode, not a filter.
+ const filterKeys = Object.keys(filters ?? {}).filter((key) => key !== 'bytecode_contract')
+ if (filters && filterKeys.length === 1 && 'bytecode' in filters) {
hogFunctionPreFilterCounter.inc({ result: 'bytecode_execution_skipped__no_filters' })
result.match = true
return result
@@ -487,7 +493,8 @@ export async function filterFunctionInstrumented(options: {
})
}
} catch (error) {
- hogFunctionFilterErrors.inc({ caller, type, reason })
+ const errorClass = classifyFilterError(error, reason, filters)
+ hogFunctionFilterErrors.inc({ caller, type, reason, class: errorClass })
logger.debug('🦔', `[${fnKind}] Error filtering function`, {
functionId: fn.id,
@@ -515,6 +522,29 @@ export async function filterFunctionInstrumented(options: {
message: `Error filtering event ${filterGlobals.uuid ?? ''}: ${error.message}`,
})
result.error = error.message
+ result.errorClass = errorClass
}
return result
}
+
+function classifyFilterError(
+ error: unknown,
+ reason: FilterErrorReason,
+ filters: HogFunctionType['filters']
+): HogErrorClass {
+ switch (reason) {
+ case 'not_compiled':
+ case 'no_bytecode':
+ // Nothing ran. The function cannot work until its owner saves it again.
+ return 'legacy'
+ case 'vm_error':
+ return classifyHogError(error, {
+ bytecodeContract: filters?.bytecode_contract,
+ runtimeContract: currentRuntimeContractHash(),
+ })
+ case 'prefilter':
+ case 'unknown':
+ // Our own code threw before or around the VM.
+ return 'platform'
+ }
+}
diff --git a/nodejs/src/cdp/utils/invocation-utils.test.ts b/nodejs/src/cdp/utils/invocation-utils.test.ts
index ccb7596594d2..ac75121965a2 100644
--- a/nodejs/src/cdp/utils/invocation-utils.test.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.test.ts
@@ -1,8 +1,10 @@
import { DateTime } from 'luxon'
+import { register } from 'prom-client'
import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'
import { createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
import { HogInputsService } from '../services/hog-inputs.service'
+import { HogFunctionType } from '../types'
import { MAX_LOG_LENGTH } from '../utils'
import { buildHogFunctionInvocations, cloneInvocation, createInvocation } from './invocation-utils'
@@ -256,6 +258,41 @@ describe('Invocation utils', () => {
])
})
+ it('labels an inputs failure with who has to act', async () => {
+ const inputsErrors = async (cls: string): Promise<number> => {
+ const metric = await register.getSingleMetric('cdp_hog_function_inputs_error')?.get()
+ return (metric?.values ?? [])
+ .filter(({ labels }) => labels.class === cls && labels.type === 'destination')
+ .reduce((sum, { value }) => sum + value, 0)
+ }
+ const before = { legacy: await inputsErrors('legacy'), data: await inputsErrors('data') }
+ const withInput = (input: {
+ value: string
+ bytecode?: unknown[]
+ templating?: 'liquid'
+ }): HogFunctionType =>
+ createHogFunction({
+ ...HOG_EXAMPLES.simple_fetch,
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ inputs_schema: [{ key: 'url', type: 'string', label: 'Webhook URL', required: true }],
+ inputs: { url: { order: 0, ...input } },
+ })
+ const fns = [
+ // A template the compiler let through with a global the runtime does not have.
+ withInput({ value: '{distinct_id}', bytecode: ['_H', 1, 32, 'distinct_id', 1, 1] }),
+ // A liquid template the renderer refuses, unchecked at save time.
+ withInput({ value: '{% if %}', templating: 'liquid' }),
+ // A value that does not fit the function it meets.
+ withInput({ value: 'x', bytecode: ['_H', 1, 32, 'bogus', 33, 1, 33, 1, 2, 'dateDiff', 3] }),
+ ]
+
+ const results = await buildHogFunctionInvocations(hogInputsService, fns, pageviewGlobals())
+
+ expect(results.invocations).toHaveLength(0)
+ expect(await inputsErrors('legacy')).toBe(before.legacy + 2)
+ expect(await inputsErrors('data')).toBe(before.data + 1)
+ })
+
it('masks a secret input quoted by the failure', async () => {
const fn = createHogFunction({
...HOG_EXAMPLES.input_printer,
diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.ts
index c7676c58f8eb..7d248757e906 100644
--- a/nodejs/src/cdp/utils/invocation-utils.ts
+++ b/nodejs/src/cdp/utils/invocation-utils.ts
@@ -16,13 +16,15 @@ import {
} from '../types'
import { HogFunctionType } from '../types'
import { getConfiguredSensitiveValues, logEntry, sanitizeLogMessage } from '../utils'
+import { currentRuntimeContractHash } from './filter-runtime'
+import { classifyHogError } from './hog-error-classification'
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'],
+ labelNames: ['type', 'class'],
})
export function createInvocation(
@@ -120,7 +122,11 @@ export async function buildHogFunctionInvocations(
),
})
- hogFunctionInputsErrors.inc({ type: hogFunction.type })
+ hogFunctionInputsErrors.inc({
+ type: hogFunction.type,
+ // Inputs are not stamped yet, so a contract error here always reads as legacy.
+ class: classifyHogError(error, { runtimeContract: currentRuntimeContractHash() }),
+ })
metrics.push({
team_id: hogFunction.team_id,
diff --git a/nodejs/tests/fixtures/hog-bytecode/06506793b2b887da1edd578c2be21b546d98a7d811ae18279981bad8c40abb27.json b/nodejs/tests/fixtures/hog-bytecode/06506793b2b887da1edd578c2be21b546d98a7d811ae18279981bad8c40abb27.json
new file mode 100644
index 000000000000..b2c84bc05661
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/06506793b2b887da1edd578c2be21b546d98a7d811ae18279981bad8c40abb27.json
@@ -0,0 +1 @@
+["_H",1,33,1,32,"bogus",2,"now",0,2,"now",0,2,"dateDiff",3,13,38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/1ff44b75dfb6adb86e98677754d9725dfa48fb112c3f8dfe1f0eee37f40e4150.json b/nodejs/tests/fixtures/hog-bytecode/1ff44b75dfb6adb86e98677754d9725dfa48fb112c3f8dfe1f0eee37f40e4150.json
new file mode 100644
index 000000000000..2cdac4757398
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/1ff44b75dfb6adb86e98677754d9725dfa48fb112c3f8dfe1f0eee37f40e4150.json
@@ -0,0 +1 @@
+["_H",1,32,"roles",32,"properties",32,"person",1,3,32,"admin",21,38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/23f56f88aab7f09b98442af791942ebfec5fe529c04cfd304a9e7bf2d9b8c4bc.json b/nodejs/tests/fixtures/hog-bytecode/23f56f88aab7f09b98442af791942ebfec5fe529c04cfd304a9e7bf2d9b8c4bc.json
new file mode 100644
index 000000000000..550531b73f0e
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/23f56f88aab7f09b98442af791942ebfec5fe529c04cfd304a9e7bf2d9b8c4bc.json
@@ -0,0 +1 @@
+["_H",1,32,"url",32,"properties",1,2,32,"(",2,"match",2,38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/581e21e76fbf23b51f9ee412b540d3661b6329d0a29c47732b0e965e93a282c5.json b/nodejs/tests/fixtures/hog-bytecode/581e21e76fbf23b51f9ee412b540d3661b6329d0a29c47732b0e965e93a282c5.json
new file mode 100644
index 000000000000..81806876bd6e
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/581e21e76fbf23b51f9ee412b540d3661b6329d0a29c47732b0e965e93a282c5.json
@@ -0,0 +1 @@
+["_H",1,2,"now",0,33,1,2,"toIntervalDay",1,32,"2026-01-01",2,"toDateTime",1,2,"dateAdd",2,13,38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/6e513787d41e08bb672887315bced14d5c2a830139c746064ddbadfbe0b5c00f.json b/nodejs/tests/fixtures/hog-bytecode/6e513787d41e08bb672887315bced14d5c2a830139c746064ddbadfbe0b5c00f.json
new file mode 100644
index 000000000000..ee8c3bee2215
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/6e513787d41e08bb672887315bced14d5c2a830139c746064ddbadfbe0b5c00f.json
@@ -0,0 +1 @@
+["_H",1,33,1,32,",",32,"tags",32,"properties",1,2,2,"splitByString",2,2,"length",1,13,38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/ac8e48ac8a08d2ed2502a04473abc9578cbd888c00ef20e3d00e7da8dd2483ec.json b/nodejs/tests/fixtures/hog-bytecode/ac8e48ac8a08d2ed2502a04473abc9578cbd888c00ef20e3d00e7da8dd2483ec.json
new file mode 100644
index 000000000000..ec35220d772d
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/ac8e48ac8a08d2ed2502a04473abc9578cbd888c00ef20e3d00e7da8dd2483ec.json
@@ -0,0 +1 @@
+["_H",1,33,0,29,40,9,33,1,36,0,6,37,0,39,-12,36,0,38,35]
diff --git a/nodejs/tests/fixtures/hog-bytecode/cb08f568209767effc9416327bf29f6b2509fe872750ea1306e4629d374689c8.json b/nodejs/tests/fixtures/hog-bytecode/cb08f568209767effc9416327bf29f6b2509fe872750ea1306e4629d374689c8.json
new file mode 100644
index 000000000000..679282eef161
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/cb08f568209767effc9416327bf29f6b2509fe872750ea1306e4629d374689c8.json
@@ -0,0 +1 @@
+["_H",1,30,32,"$virt_is_bot",1,1,11,38]
diff --git a/posthog/cdp/filter_globals.json b/posthog/cdp/filter_globals.json
index ef8511fd0af0..a3b949873b27 100644
--- a/posthog/cdp/filter_globals.json
+++ b/posthog/cdp/filter_globals.json
@@ -1,5 +1,6 @@
{
- "$comment": "Generated. Do not edit: run `pnpm --filter=@posthog/nodejs run build:filter-globals`. roots are the data globals the CDP filter runtime builds for a hog function. callables are the standard-library names the VM hands back as values and can then invoke, so they are the ones a filter can pass as a callback. functions are every standard-library name a filter can call directly, with the argument count the VM enforces as [min, max]. template_roots are the names an input template can read. Django reads this to refuse a filter or an input the runtime could not evaluate.",
+ "$comment": "Generated. Do not edit: run `pnpm --filter=@posthog/nodejs run build:filter-globals`. roots are the data globals the CDP filter runtime builds for a hog function. callables are the standard-library names the VM hands back as values and can then invoke, so they are the ones a filter can pass as a callback. functions are every standard-library name a filter can call directly, with the argument count the VM enforces as [min, max]. template_roots are the names an input template can read. Django reads this to refuse a filter or an input the runtime could not evaluate. contract is a hash of the rest, stamped on compiled bytecode.",
+ "contract": "bfd6ece60e41383c",
"roots": [
"$group_0",
"$group_1",