:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): reject filters that read globals the runtime does not have (#103913)
Meikel Ratzdea54c922e7a
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex 1d922e31541b..17abe3381ce7 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -129,6 +129,12 @@ jobs:- 'posthog/management/commands/setup_test_environment.py'- 'posthog/migrations/**'- 'posthog/plugins/**'+ # Django reads this to decide which filter globals it accepts, and the only+ # check that it still matches the runtime type is a jest test.+ - 'posthog/cdp/filter_globals.json'+ # The tables that file is generated from. A standard-library change+ # must run the parity test that shows the file went stale.+ - 'common/hogvm/typescript/src/**'# Compose files only, no Dockerfile glob: these jobs run the suites from# source via pnpm and the compose stack's only build contexts are rust/,# so no app image is built here. Dockerfile.node is gated separately in@@ -150,6 +156,9 @@ jobs:# Anything here invalidates jest's view of the module graph, or changes# the native addons every suite links, so no narrowed run can be trusted.node_full:+ # readFileSync, so jest cannot reach the parity test through --findRelatedTests.+ - 'posthog/cdp/filter_globals.json'+ - 'common/hogvm/typescript/src/**'- '.github/scripts/jest-retries.cjs'- 'patches/[email protected]'- 'nodejs/jest*.config.js'diff --git a/common/hogvm/typescript/src/index.ts b/common/hogvm/typescript/src/index.tsindex 81a1cb7147b3..0d06f9f1161b 100644--- a/common/hogvm/typescript/src/index.ts+++ b/common/hogvm/typescript/src/index.ts@@ -2,6 +2,7 @@ export * from './constants'export * from './execute'export * from './objects'export * from './operation'+export * from './stl/bytecode'export * from './stl/stl'export * from './stl/print'export * from './types'diff --git a/nodejs/bin/build-filter-globals.ts b/nodejs/bin/build-filter-globals.tsnew file mode 100644index 000000000000..ed10fe7937a3--- /dev/null+++ b/nodejs/bin/build-filter-globals.ts@@ -0,0 +1,12 @@+import { writeFileSync } from 'fs'+import { join } from 'path'++import {+ FILTER_GLOBALS_RELATIVE_PATH,+ describeFilterRuntime,+ renderFilterGlobalsFile,+} from '../src/cdp/utils/filter-runtime'++const target = join(__dirname, '..', '..', FILTER_GLOBALS_RELATIVE_PATH)+writeFileSync(target, renderFilterGlobalsFile(describeFilterRuntime()))+console.info(`wrote ${target}`)diff --git a/nodejs/package.json b/nodejs/package.jsonindex e02a24a12230..1accd8a759f3 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -27,6 +27,7 @@"lint:fix": "eslint . --fix && oxlint -c .oxlintrc.nodejs.json . --fix","check:boundaries": "node bin/check-ingestion-boundaries.mjs","check:boundaries:write": "node bin/check-ingestion-boundaries.mjs --write",+ "build:filter-globals": "pnpm --filter=@posthog/hogvm build && NODE_ENV=test tsx bin/build-filter-globals.ts","format": "prettier --write .","format:check": "prettier --check .","prepublishOnly": "pnpm build",diff --git a/nodejs/src/cdp/utils/filter-runtime.test.ts b/nodejs/src/cdp/utils/filter-runtime.test.tsnew file mode 100644index 000000000000..70880925e87f--- /dev/null+++ b/nodejs/src/cdp/utils/filter-runtime.test.ts@@ -0,0 +1,91 @@+import { readFileSync } from 'fs'+import { join } from 'path'++import { parseJSON } from '~/common/utils/json-parse'++import { FILTER_GLOBALS_RELATIVE_PATH, describeFilterRuntime, renderFilterGlobalsFile } 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', () => {+ // 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.+ 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)+ )+ }+ expect(actual).toEqual(expected)+ })++ it('describes what a hog function is actually evaluated with', () => {+ const { roots, callables, functions } = describeFilterRuntime()+ expect(roots).toEqual(expect.arrayContaining(['event', 'person', 'properties', 'group_0', '$group_4']))+ // In the type, but built only by the hogflow conditional-branch path, which does not compile+ // through compile_filters_bytecode. Listing it would let a destination save a filter that throws.+ expect(roots).not.toContain('cohort_ids')+ expect(callables).toEqual(expect.arrayContaining(['lower', 'toString']))+ // Resolvable but async, and the filter path runs with maxAsyncSteps 0.+ expect(callables).not.toContain('sleep')+ // Resolvable, but the closure it resolves to cannot be invoked. Calling arrayMap by name is+ // unaffected, because a call is not read as a global.+ expect(callables).not.toContain('arrayMap')+ expect(functions).toEqual(expect.objectContaining({ lower: [1, 1], arrayMap: [2, 2], sortableSemver: [1, 1] }))+ expect(functions).not.toHaveProperty('sleep')+ expect(callables).not.toContain('print')+ expect(functions).not.toHaveProperty('print')+ })++ it('agrees with what the VM does when asked', async () => {+ // The tables say what resolves; this checks the tables mean what we think they mean. A filter+ // passes a name as a callback, so resolving it is only half of what has to work: the other half+ // is the VM invoking the closure it got back. Passing one through arrayMap covers both.+ const asCallback = async (name: string): Promise<string> => {+ const bytecode = ['_H', 1, 32, name, 1, 1, 32, 'A', 43, 1, 2, 'arrayMap', 2]+ const { error, execResult } = await execHog(bytecode, { globals: {} })+ return String(error ?? execResult?.error ?? '')+ }+ for (const name of ['lower', 'toString']) {+ expect(await asCallback(name)).toBe('')+ }+ expect(await asCallback('definitelyNotAGlobal')).toContain('Global variable not found')+ // The half a resolution-only check misses, and the reason arrayMap is not offered as one.+ expect(await asCallback('arrayMap')).toContain('Unsupported function call')++ // Every offered name has to survive both halves, or a filter that passes it saves and then+ // throws on every event. Other errors are the callback meeting one string argument, not the+ // contract breaking.+ const contractErrors = ['Global variable not found', 'Unsupported function call']+ const broken: string[] = []+ for (const name of describeFilterRuntime().callables) {+ const message = await asCallback(name)+ if (contractErrors.some((error) => message.includes(error))) {+ broken.push(`${name}: ${message}`)+ }+ }+ expect(broken).toEqual([])++ // Django checks a direct call against functions, so every name there has to run as one.+ const calledDirectly = async (name: string): Promise<string> => {+ const { error, execResult } = await execHog(['_H', 1, 2, name, 0], { globals: {} })+ return String(error ?? execResult?.error ?? '')+ }+ const notCallable: string[] = []+ for (const name of Object.keys(describeFilterRuntime().functions)) {+ const message = await calledDirectly(name)+ if (contractErrors.some((error) => message.includes(error))) {+ notCallable.push(`${name}: ${message}`)+ }+ }+ expect(notCallable).toEqual([])+ expect(await calledDirectly('definitelyNotAFunction')).toContain('Unsupported function call')+ })+})diff --git a/nodejs/src/cdp/utils/filter-runtime.ts b/nodejs/src/cdp/utils/filter-runtime.tsnew file mode 100644index 000000000000..7c522794e039--- /dev/null+++ b/nodejs/src/cdp/utils/filter-runtime.ts@@ -0,0 +1,128 @@+import { ASYNC_STL, BYTECODE_STL, STL } from '@posthog/hogvm'++import { ClickHouseTimestamp, ProjectId, RawClickHouseEvent } from '../../types'+import { HogFunctionInvocationGlobals } from '../types'+import { convertClickhouseRawEventToFilterGlobals, convertToHogFunctionFilterGlobal } from './hog-function-filtering'++/** Where Django reads the result. Relative to the repository root. */+export const FILTER_GLOBALS_RELATIVE_PATH = 'posthog/cdp/filter_globals.json'++export type FilterRuntime = {+ /** Data globals every filter compiled by compile_filters_bytecode is evaluated with. */+ roots: string[]+ /** Standard-library names the VM hands back as values and can then invoke, so a filter can pass+ * them as callbacks. */+ callables: string[]+ /**+ * Every standard-library name a filter can call directly, the bytecode-implemented ones included, with+ * the argument count the VM enforces as [min, max]. A null max means unbounded.+ */+ functions: Record<string, [number, number | null]>+}++// These stand for the callers of compile_filters_bytecode: hog function filters, evaluated by the two+// builders below. A new caller with a different globals shape has to be added here, or Django will+// validate against the wrong set. Every input is populated so a builder that only sets a key when its+// input is present still sets it.+const invocationGlobals: Pick<HogFunctionInvocationGlobals, 'event' | 'person' | 'groups' | 'variables'> = {+ event: {+ uuid: '00000000-0000-0000-0000-000000000001',+ event: '$pageview',+ distinct_id: 'distinct-id',+ elements_chain: 'a:href="https://example.com"',+ properties: { $current_url: 'https://example.com' },+ timestamp: '2026-01-01T00:00:00.000Z',+ url: 'https://example.com/events/1',+ },+ person: {+ id: '00000000-0000-0000-0000-000000000002',+ name: 'example',+ url: 'https://example.com/persons/1',+ properties: { email: '[email protected]' },+ },+ groups: {+ organization: { id: 'org-1', type: 'organization', index: 0, url: '', properties: { plan: 'pro' } },+ },+ variables: { threshold: 10 },+}++const rawEvent: RawClickHouseEvent = {+ uuid: '00000000-0000-0000-0000-000000000001',+ event: '$pageview',+ team_id: 1,+ project_id: 1 as ProjectId,+ distinct_id: 'distinct-id',+ timestamp: '2026-01-01 00:00:00.000000' as ClickHouseTimestamp,+ created_at: '2026-01-01 00:00:00.000000' as ClickHouseTimestamp,+ properties: JSON.stringify({ $current_url: 'https://example.com' }),+ elements_chain: 'a:href="https://example.com"',+ person_id: '00000000-0000-0000-0000-000000000002',+ person_properties: JSON.stringify({ email: '[email protected]' }),+ group0_properties: JSON.stringify({ plan: 'pro' }),+ person_mode: 'full',+ historical_migration: false,+}++// Below these the builders have almost certainly thrown inside and been swallowed; a near-empty+// file would otherwise pass the staleness check and reject every filter.+const MIN_ROOTS = 20+const MIN_CALLABLES = 100++/** Asks the runtime what it resolves, rather than transcribing a type or a table by hand. */+export function describeFilterRuntime(): FilterRuntime {+ const fromInvocation = Object.keys(convertToHogFunctionFilterGlobal(invocationGlobals)).sort()+ const fromRawEvent = Object.keys(convertClickhouseRawEventToFilterGlobals(rawEvent)).sort()+ if (JSON.stringify(fromInvocation) !== JSON.stringify(fromRawEvent)) {+ throw new Error(+ `The two filter-globals builders disagree.\n invocation: ${fromInvocation.join(', ')}\n raw event: ${fromRawEvent.join(', ')}`+ )+ }++ // BYTECODE_STL is left out. GET_GLOBAL hands back a closure for one of its names, but CALL_LOCAL+ // resolves an 'stl' closure in STL only, so invoking that closure throws. Calling the same name+ // directly is unaffected: a call compiles to CALL_GLOBAL, which runs the BYTECODE_STL bytecode.+ // ASYNC_STL is a separate table today, so this removes nothing. It stays because GET_GLOBAL checks+ // ASYNC_STL first: a name added to both would be async at runtime, and the filter path allows no+ // async steps, so it must not be offered as a callable.+ // print writes to the process's stdout. The function body path replaces it with a logger; the+ // filter path runs the standard library as is, so a filter must not be able to reach it.+ const offered = (name: string): boolean => !Object.hasOwn(ASYNC_STL, name) && name !== 'print'+ const callables = Object.keys(STL).filter(offered).sort()+ const functions: Record<string, [number, number | null]> = {}+ for (const name of Object.keys(STL).filter(offered).sort()) {+ functions[name] = [STL[name].minArgs ?? 0, STL[name].maxArgs ?? null]+ }+ for (const name of Object.keys(BYTECODE_STL).filter(offered).sort()) {+ // The VM checks a bytecode function for exactly its declared parameters.+ functions[name] ??= [BYTECODE_STL[name][0].length, BYTECODE_STL[name][0].length]+ }++ if (fromInvocation.length < MIN_ROOTS || Object.keys(functions).length < MIN_CALLABLES) {+ throw new Error(+ `Suspiciously small runtime description: ${fromInvocation.length} roots, ${callables.length} callables`+ )+ }+ return { roots: fromInvocation, callables, functions }+}++export function renderFilterGlobalsFile(runtime: FilterRuntime): string {+ return (+ JSON.stringify(+ {+ $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]. Django reads this to ' ++ 'refuse a filter the runtime could not evaluate.',+ roots: runtime.roots,+ callables: runtime.callables,+ functions: runtime.functions,+ },+ null,+ // Matches what the pre-commit hook (bin/hogli format:yaml) writes, so a regenerate is a no-op.+ 4+ ) + '\n'+ )+}diff --git a/posthog/cdp/filter_globals.json b/posthog/cdp/filter_globals.jsonnew file mode 100644index 000000000000..034f5147aca8--- /dev/null+++ b/posthog/cdp/filter_globals.json@@ -0,0 +1,290 @@+{+ "$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]. Django reads this to refuse a filter the runtime could not evaluate.",+ "roots": [+ "$group_0",+ "$group_1",+ "$group_2",+ "$group_3",+ "$group_4",+ "distinct_id",+ "elements_chain",+ "elements_chain_elements",+ "elements_chain_href",+ "elements_chain_ids",+ "elements_chain_texts",+ "event",+ "group_0",+ "group_1",+ "group_2",+ "group_3",+ "group_4",+ "pdi",+ "person",+ "properties",+ "timestamp",+ "uuid",+ "variables"+ ],+ "callables": [+ "Error",+ "HogError",+ "JSONExtract",+ "JSONExtractArrayRaw",+ "JSONExtractBool",+ "JSONExtractFloat",+ "JSONExtractInt",+ "JSONExtractString",+ "JSONHas",+ "JSONLength",+ "NotImplementedError",+ "RetryError",+ "addDays",+ "and",+ "arrayPopBack",+ "arrayPopFront",+ "arrayPushBack",+ "arrayPushFront",+ "arrayReverse",+ "arrayReverseSort",+ "arraySort",+ "arrayStringConcat",+ "assumeNotNull",+ "base64Decode",+ "base64Encode",+ "coalesce",+ "concat",+ "dateAdd",+ "dateDiff",+ "dateTrunc",+ "decodeURLComponent",+ "empty",+ "encodeURLComponent",+ "equals",+ "extract",+ "extractRegex",+ "floor",+ "formatDateTime",+ "fromUnixTimestamp",+ "fromUnixTimestampMilli",+ "generateUUIDv4",+ "greater",+ "greaterOrEquals",+ "has",+ "if",+ "ifNull",+ "ilike",+ "in",+ "indexOf",+ "isIPAddressInRange",+ "isNotNull",+ "isNull",+ "isValidJSON",+ "jsonParse",+ "jsonStringify",+ "keys",+ "length",+ "less",+ "lessOrEquals",+ "like",+ "lower",+ "match",+ "md5",+ "md5Hex",+ "min2",+ "minus",+ "multiIf",+ "multiSearchAnyCaseInsensitive",+ "not",+ "notEmpty",+ "notEquals",+ "notILike",+ "notLike",+ "now",+ "or",+ "plus",+ "position",+ "positionCaseInsensitive",+ "randomFloat",+ "range",+ "replaceAll",+ "replaceOne",+ "reverse",+ "round",+ "sha1",+ "sha1Hex",+ "sha1HmacChain",+ "sha1HmacChainHex",+ "sha256",+ "sha256Hex",+ "sha256HmacChain",+ "sha256HmacChainHex",+ "splitByString",+ "startsWith",+ "substring",+ "toDate",+ "toDateTime",+ "toFloat",+ "toInt",+ "toIntervalDay",+ "toIntervalHour",+ "toIntervalMinute",+ "toIntervalMonth",+ "toMonth",+ "toStartOfDay",+ "toStartOfHour",+ "toStartOfMonth",+ "toStartOfWeek",+ "toString",+ "toTimeZone",+ "toUUID",+ "toUnixTimestamp",+ "toUnixTimestampMilli",+ "toYYYYMM",+ "toYear",+ "today",+ "trim",+ "trimLeft",+ "trimRight",+ "tryBase64Decode",+ "tryDecodeURLComponent",+ "tuple",+ "typeof",+ "upper",+ "values"+ ],+ "functions": {+ "Error": [0, 2],+ "HogError": [1, 3],+ "JSONExtract": [2, null],+ "JSONExtractArrayRaw": [1, null],+ "JSONExtractBool": [1, null],+ "JSONExtractFloat": [1, null],+ "JSONExtractInt": [1, null],+ "JSONExtractString": [1, null],+ "JSONHas": [1, null],+ "JSONLength": [1, null],+ "NotImplementedError": [0, 2],+ "RetryError": [0, 2],+ "addDays": [2, 2],+ "and": [1, null],+ "arrayPopBack": [1, 1],+ "arrayPopFront": [1, 1],+ "arrayPushBack": [2, 2],+ "arrayPushFront": [2, 2],+ "arrayReverse": [1, 1],+ "arrayReverseSort": [1, null],+ "arraySort": [1, null],+ "arrayStringConcat": [1, 2],+ "assumeNotNull": [1, 1],+ "base64Decode": [1, 1],+ "base64Encode": [1, 1],+ "coalesce": [1, null],+ "concat": [1, null],+ "dateAdd": [3, 3],+ "dateDiff": [3, 3],+ "dateTrunc": [2, 3],+ "decodeURLComponent": [1, 1],+ "empty": [1, 1],+ "encodeURLComponent": [1, 1],+ "equals": [2, 2],+ "extract": [2, 2],+ "extractRegex": [2, 2],+ "floor": [1, 2],+ "formatDateTime": [2, 3],+ "fromUnixTimestamp": [1, 1],+ "fromUnixTimestampMilli": [1, 1],+ "generateUUIDv4": [0, 0],+ "greater": [2, 2],+ "greaterOrEquals": [2, 2],+ "has": [2, 2],+ "if": [3, 3],+ "ifNull": [2, 2],+ "ilike": [2, 2],+ "in": [2, 2],+ "indexOf": [2, 2],+ "isIPAddressInRange": [2, 2],+ "isNotNull": [1, 1],+ "isNull": [1, 1],+ "isValidJSON": [1, 1],+ "jsonParse": [1, 1],+ "jsonStringify": [1, 2],+ "keys": [1, 1],+ "length": [1, 1],+ "less": [2, 2],+ "lessOrEquals": [2, 2],+ "like": [2, 2],+ "lower": [1, 1],+ "match": [2, 2],+ "md5": [1, 2],+ "md5Hex": [1, 1],+ "min2": [2, 2],+ "minus": [2, 2],+ "multiIf": [3, null],+ "multiSearchAnyCaseInsensitive": [2, 2],+ "not": [1, 1],+ "notEmpty": [1, 1],+ "notEquals": [2, 2],+ "notILike": [2, 2],+ "notLike": [2, 2],+ "now": [0, 1],+ "or": [1, null],+ "plus": [2, 2],+ "position": [2, 3],+ "positionCaseInsensitive": [2, 3],+ "randomFloat": [0, 0],+ "range": [1, 2],+ "replaceAll": [3, 3],+ "replaceOne": [3, 3],+ "reverse": [1, 1],+ "round": [1, 2],+ "sha1": [1, 2],+ "sha1Hex": [1, 1],+ "sha1HmacChain": [1, 2],+ "sha1HmacChainHex": [1, 1],+ "sha256": [1, 2],+ "sha256Hex": [1, 1],+ "sha256HmacChain": [1, 2],+ "sha256HmacChainHex": [1, 1],+ "splitByString": [2, 3],+ "startsWith": [2, 2],+ "substring": [2, 3],+ "toDate": [1, 1],+ "toDateTime": [1, 2],+ "toFloat": [1, 1],+ "toInt": [1, 1],+ "toIntervalDay": [1, 1],+ "toIntervalHour": [1, 1],+ "toIntervalMinute": [1, 1],+ "toIntervalMonth": [1, 1],+ "toMonth": [1, 1],+ "toStartOfDay": [1, 2],+ "toStartOfHour": [1, 1],+ "toStartOfMonth": [1, 1],+ "toStartOfWeek": [1, 2],+ "toString": [1, 2],+ "toTimeZone": [2, 2],+ "toUUID": [1, 1],+ "toUnixTimestamp": [1, 2],+ "toUnixTimestampMilli": [1, 2],+ "toYYYYMM": [1, 1],+ "toYear": [1, 1],+ "today": [0, 0],+ "trim": [1, 2],+ "trimLeft": [1, 2],+ "trimRight": [1, 2],+ "tryBase64Decode": [1, 1],+ "tryDecodeURLComponent": [1, 1],+ "tuple": [0, null],+ "typeof": [1, 1],+ "upper": [1, 1],+ "values": [1, 1],+ "arrayCount": [2, 2],+ "arrayExists": [2, 2],+ "arrayFilter": [2, 2],+ "arrayMap": [2, 2],+ "arrayReduce": [3, 3],+ "inCohort": [2, 2],+ "notInCohort": [2, 2],+ "sortableSemver": [1, 1]+ }+}diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.pyindex 1d56e55d7f2a..e01b46db136e 100644--- a/posthog/cdp/filters.py+++ b/posthog/cdp/filters.py@@ -1,3 +1,5 @@+import json+from pathlib import Pathfrom typing import Any, Optionalfrom django.conf import settings@@ -359,6 +361,21 @@ class _LowerConstantMembership(CloningVisitor):return super().visit_compare_operation(node)+# Loaded rather than listed: the set belongs to the runtime, and a stale copy here would reject a+# filter people can legitimately write. A test in the nodejs package pins the file to the type.+_RUNTIME = json.loads((Path(__file__).parent / "filter_globals.json").read_text())+# Callables belong here because the VM resolves a bare standard-library name through the same+# GET_GLOBAL path, so `arrayMap(lower, ...)` is a working filter rather than an unknown global.+# Generated from the runtime by `pnpm --filter=@posthog/nodejs run build:filter-globals`.+FILTER_GLOBALS: set[str] = set(_RUNTIME["roots"]) | set(_RUNTIME["callables"])+# The Python compiler knows its own standard library, which is not the one the Node VM runs.+FILTER_FUNCTIONS: dict[str, tuple[int, Optional[int]]] = {+ name: (arity[0], arity[1]) for name, arity in _RUNTIME["functions"].items()+}++_UNKNOWN_GLOBAL = "Unknown global variable: "++def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optional[dict[int, Action]] = None) -> dict:filters = filters or {}try:@@ -367,9 +384,22 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optioraise Exception("Select queries are not allowed in filters")expr = _LowerConstantMembership().visit(expr)- context = HogQLContext(team_id=team.id)+ # Declaring the globals turns the compiler's field resolution into a check: it warns on a+ # root that is neither a local, an upvalue, nor one of ours.+ context = HogQLContext(+ team_id=team.id, globals=dict.fromkeys(FILTER_GLOBALS), allowed_functions=FILTER_FUNCTIONS+ )filters["bytecode"] = create_bytecode(expr, context=context).bytecode+ unknown = sorted(+ {w.message.removeprefix(_UNKNOWN_GLOBAL) for w in context.warnings if w.message.startswith(_UNKNOWN_GLOBAL)}+ )+ if unknown:+ raise Exception(+ f"Real-time filters cannot read {', '.join(unknown)}. "+ f"Check the spelling, or use a field or function that real-time filters support."+ )+# context.errors here only contains "function not implemented" errors from the# bytecode compiler (the resolver doesn't run during create_bytecode). These are# genuinely fatal — the bytecode would reference a non-existent function at runtime.diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.pyindex bf88c68efe0c..4c13c2193208 100644--- a/posthog/cdp/test/test_filters.py+++ b/posthog/cdp/test/test_filters.py@@ -119,6 +119,154 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest)assert response["bytecode_error"] == "Select queries are not allowed in filters"+ def test_filters_raise_on_a_global_the_runtime_does_not_have(self):+ # $virt_is_bot exists in HogQL query context but not in the globals the filter path+ # builds, so it compiles clean and then raises on every event the destination is offered.+ response = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "$virt_is_bot"}]},+ team=self.team,+ )+ assert "$virt_is_bot" in response["bytecode_error"]+ assert response["bytecode"] is None++ def test_filters_allow_a_global_the_runtime_does_have(self):+ response = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "person.properties.email is not null"}]},+ team=self.team,+ )+ assert "bytecode_error" not in response++ def test_filters_allow_what_the_other_consumers_compile(self):+ # Error tracking alerts and AI observability evaluations compile through this function too,+ # and error tracking turns any bytecode_error into a refused save. Their surfaces reduce to+ # roots the runtime provides, and this keeps that true.+ alert = compile_filters_bytecode(+ filters={+ "events": [+ {+ "id": "$exception",+ "type": "events",+ "properties": [{"key": "$exception_type", "value": "TypeError", "type": "event"}],+ }+ ]+ },+ team=self.team,+ )+ assert "bytecode_error" not in alert++ evaluation = compile_filters_bytecode(+ filters={+ "properties": [{"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}]+ },+ team=self.team,+ )+ assert "bytecode_error" not in evaluation++ def test_filters_reject_a_global_only_some_callers_supply(self):+ # cohort_ids is built only by hogflow_conditional_branch, and only when the condition+ # references cohorts. Nothing this function compiles is ever evaluated with it present.+ response = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "has(cohort_ids, 1)"}]},+ team=self.team,+ )+ assert "cohort_ids" in response["bytecode_error"]++ def test_filters_allow_a_named_stl_callback(self):+ # The VM resolves a bare standard-library name through GET_GLOBAL and returns the callable,+ # so this filter runs. Only the async one cannot, because the filter path allows no async steps.+ ok = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "arrayMap(lower, ['A'])[1] = 'a'"}]},+ team=self.team,+ )+ assert "bytecode_error" not in ok++ rejected = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "arrayMap(sleep, [1])[1] = 1"}]},+ team=self.team,+ )+ assert "sleep" in rejected["bytecode_error"]++ # A bytecode standard-library name resolves to a closure the VM then refuses to call, so a+ # filter passing one as a callback throws on every event.+ not_invocable = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "arrayMap(sortableSemver, ['1.2.3'])[1] != []"}]},+ team=self.team,+ )+ assert "sortableSemver" in not_invocable["bytecode_error"]++ # A direct call compiles to a different instruction, which does run the same name.+ called_directly = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "sortableSemver('1.2.3')[1] = 1"}]},+ team=self.team,+ )+ assert "bytecode_error" not in called_directly++ def test_filters_reject_a_function_the_runtime_does_not_have(self):+ # max2 exists in the Python standard library and not in the Node VM. A data global such as+ # event is not callable either, because the VM resolves a direct call against its function+ # tables and never against the globals it was given.+ for key in ("max2(1, 2) > 1", "sleep(1) = 1", "event() = 'x'", "properties() = 'x'"):+ response = compile_filters_bytecode(filters={"properties": [{"type": "hogql", "key": key}]}, team=self.team)+ assert response.get("bytecode_error"), key+ assert key.split("(")[0] in response["bytecode_error"]++ def test_filters_reject_a_call_with_the_wrong_number_of_arguments(self):+ # Valid HogQL for a query, where dateAdd takes two arguments, and a run-time error in the VM,+ # where it takes three.+ for key, expected in (+ ("lower() = 'a'", "`lower` takes exactly 1 arguments, got 0"),+ ("inCohort(1)", "`inCohort` takes exactly 2 arguments, got 1"),+ ("dateAdd(toIntervalDay(1), timestamp) > now()", "`dateAdd` takes exactly 3 arguments, got 2"),+ ):+ response = compile_filters_bytecode(filters={"properties": [{"type": "hogql", "key": key}]}, team=self.team)+ assert expected in (response.get("bytecode_error") or ""), key++ def test_filters_reject_what_the_compiler_lowers_before_the_generic_check(self):+ for key, expected in (+ ("if(true, true)", "`if` takes exactly 3 arguments, got 2"),+ ("if(true, true, false, $virt_is_bot)", "`if` takes exactly 3 arguments, got 4"),+ ("sql(event) = 1", "`sql` is not implemented"),+ ("print(person.properties.email) = ''", "`print` is not implemented"),+ (+ "person.properties.email.startsWith('a')",+ "`person.properties.email.startsWith` is a value, not a function",+ ),+ ("(event)()", "`event` is a value, not a function"),+ ("multiIf(true, true, false, true)", "`multiIf` takes an odd number of arguments, got 4"),+ ):+ response = compile_filters_bytecode(filters={"properties": [{"type": "hogql", "key": key}]}, team=self.team)+ assert expected in (response.get("bytecode_error") or ""), key++ # The shape with a value to fall back to still compiles.+ odd = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "multiIf(true, true, false, true, false)"}]},+ team=self.team,+ )+ assert "bytecode_error" not in odd++ # A lambda parameter is a variable, and a variable that holds a function can be called.+ allowed = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "arrayMap(f -> f(1), [x -> x])[1] = 1"}]}, team=self.team+ )+ assert "bytecode_error" not in allowed++ def test_filters_allow_group_globals(self):+ response = compile_filters_bytecode(+ filters={+ "properties": [{"type": "hogql", "key": "group_0.properties.name = 'a' and $group_1 is not null"}]+ },+ team=self.team,+ )+ assert "bytecode_error" not in response++ def test_filters_allow_a_lambda_parameter(self):+ # The parameter is a local, not a global. Reading the chain off the AST would reject this.+ response = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "arrayExists(x -> x = 'a', elements_chain_texts)"}]},+ team=self.team,+ )+ assert "bytecode_error" not in response+def test_filters_events(self):bytecode = self.filters_to_bytecode(filters={"events": self.filters["events"]})assert bytecode == [diff --git a/posthog/hogql/compiler/bytecode.py b/posthog/hogql/compiler/bytecode.pyindex 99a2a5e29d87..c2bf85fe22dd 100644--- a/posthog/hogql/compiler/bytecode.py+++ b/posthog/hogql/compiler/bytecode.py@@ -449,7 +449,56 @@ class BytecodeCompiler(Visitor):else:raise QueryError(f"Constant type `{type(node.value)}` is not supported")+ def _check_call_arity(self, node: ast.Call, arg_count: int) -> None:+ # The VM rejects a wrong argument count at run time, so a caller that declares its functions+ # gets the same check here, where the person writing the expression can see it.+ if self.context.allowed_functions is None or node.name not in self.context.allowed_functions:+ return+ min_args, max_args = self.context.allowed_functions[node.name]+ if min_args <= arg_count and (max_args is None or arg_count <= max_args):+ return+ if max_args is None:+ expected = f"at least {min_args}"+ elif min_args == max_args:+ expected = f"exactly {min_args}"+ else:+ expected = f"{min_args} to {max_args}"+ self.context.add_error(+ start=node.start,+ end=node.end,+ message=f"Hog function `{node.name}` takes {expected} arguments, got {arg_count}",+ )++ def _names_a_variable(self, name: str) -> bool:+ return any(local.name == name for local in self.locals) or self._resolve_upvalue(name) != -1++ def _check_declared_call(self, node: ast.Call) -> None:+ # Runs before the intrinsics below lower `if`, `sql` and the like, which otherwise never reach+ # the generic check and would accept an argument count or a name the runtime does not have.+ if self.context.allowed_functions is None or self._names_a_variable(node.name):+ return+ if node.name in self.supported_functions:+ return+ if node.name not in self.context.allowed_functions:+ self.context.add_error(+ start=node.start, end=node.end, message=f"Hog function `{node.name}` is not implemented"+ )+ return+ arg_count = len(node.params if node.params is not None else node.args)+ self._check_call_arity(node, arg_count)+ # multiIf pairs every condition with a value and needs a last one to fall back to. An+ # argument count is all the contract can carry, so it cannot say that, and an even count+ # lowers into bytecode that leaves nothing to return when no condition matches.+ if node.name == "multiIf" and arg_count > 3 and arg_count % 2 == 0:+ self.context.add_error(+ start=node.start,+ end=node.end,+ message=f"Hog function `multiIf` takes an odd number of arguments, got {arg_count}. "+ f"Add a last value to fall back to.",+ )+def visit_call(self, node: ast.Call):+ self._check_declared_call(node)if node.name == "not" and len(node.args) == 1:return [*self.visit(node.args[0]), Operation.NOT]if node.name == "and" and len(node.args) > 1:@@ -529,10 +578,20 @@ class BytecodeCompiler(Visitor):if upvalue != -1:response.extend([Operation.GET_UPVALUE, upvalue, Operation.CALL_LOCAL, len(args)])else:- if self.context.globals and node.name in self.context.globals:+ # The VM resolves a direct call against its function tables only, never against+ # the globals it was given. A caller that declares allowed_functions has named+ # every function its runtime can invoke, so a data global of the same name is not+ # one of them.+ if (+ self.context.allowed_functions is None+ and self.context.globals+ and node.name in self.context.globals+ ):self.context.add_notice(start=node.start, end=node.end, message="Global variable: " + str(node.name))+ elif self.context.allowed_functions is not None:+ pass # checked by _check_declared_callelif node.name in self.supported_functions or node.name in STL or node.name in BYTECODE_STL:passelse:@@ -552,6 +611,19 @@ class BytecodeCompiler(Visitor):return responsedef visit_expr_call(self, node: ast.ExprCall):+ # `person.properties.email.startsWith('a')` parses as a call on a value. The runtime resolves+ # the value, which is never a function, so a caller with a declared contract refuses it.+ if (+ self.context.allowed_functions is not None+ and isinstance(node.expr, ast.Field)+ and not self._names_a_variable(str(node.expr.chain[0]))+ ):+ self.context.add_error(+ start=node.start,+ end=node.end,+ message=f"`{'.'.join(str(part) for part in node.expr.chain)}` is a value, not a function. "+ f"Write the function name first, as in lower(properties.name)",+ )response = []for expr in node.args:response.extend(self.visit(expr))diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex 112e53faabac..232ad283d120 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -101,6 +101,9 @@ class HogQLContext:top_level_settings: dict[str, object] = field(default_factory=dict)# Globals that will be resolved in the context of the queryglobals: Optional[dict] = None+ # Standard-library names the bytecode compiler accepts for a direct call. The Python and Node+ # standard libraries differ, so a caller whose bytecode runs elsewhere names what it can execute.+ allowed_functions: Optional[dict[str, tuple[int, Optional[int]]]] = Noneproperty_type_overrides: Optional[dict[str, str]] = None# Per-query data that query runners want to ingest into the HogQL resolution (e.g. pending updates# merged into a table via UNION ALL in error tracking).