: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(hogvm): validate builtin arity in the CALL_GLOBAL path (#81140)
posthog[bot]d4d27ce2a16e
diff --git a/common/hogvm/CHANGELOG.md b/common/hogvm/CHANGELOG.mdindex ae93724b1b7c..5101daf7f7b0 100644--- a/common/hogvm/CHANGELOG.md+++ b/common/hogvm/CHANGELOG.md@@ -1,5 +1,23 @@# HogQL bytecode changelog+## 2026-08-27 - 1.0.69++The VM checks the argument count of a standard library function before it calls it. No bytecode+operations changed.++A call with too few or too many arguments fails with `Function <name> requires at least N arguments`+or `Function <name> requires at most N arguments`. The VM applied this check only to a standard+library function held in a variable. A direct call skipped it and ran with the wrong number of+arguments.++Three functions now accept argument counts that they always supported but that the VM refused:++```bash+jsonStringify(value, indent) # second argument indents the output+JSONLength(value) # path arguments are optional+and(a), or(a, b, c) # both take one or more arguments+```+## 2026-08-04 - 1.0.68Added SHA-1 primitives to the standard library. No bytecode operations changed.diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.pyindex 5cbf21a8e20b..b26f1057122e 100644--- a/common/hogvm/python/execute.py+++ b/common/hogvm/python/execute.py@@ -555,11 +555,16 @@ def execute_bytecode(push_stack(functions[name](*args))elif name in STL:check_allowed(name)+ stl_fn = STL[name]+ if stl_fn.minArgs is not None and arg_count < stl_fn.minArgs:+ raise HogVMException(f"Function {name} requires at least {stl_fn.minArgs} arguments")+ if stl_fn.maxArgs is not None and arg_count > stl_fn.maxArgs:+ raise HogVMException(f"Function {name} requires at most {stl_fn.maxArgs} arguments")if version == 0:args = [pop_stack() for _ in range(arg_count)]else:args = stack_keep_first_elements(len(stack) - arg_count)- push_stack(STL[name].fn(args, team, stdout, remaining_timeout()))+ push_stack(stl_fn.fn(args, team, stdout, remaining_timeout()))elif name in BYTECODE_STL:arg_names = BYTECODE_STL[name][0]if len(arg_names) != arg_count:diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 65f69f256512..63f5c4a7edbf 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -1016,10 +1016,10 @@ STL: dict[str, STLFunction] = {"reverse": STLFunction(fn=lambda args, team, stdout, timeout: args[0][::-1], minArgs=1, maxArgs=1),"print": STLFunction(fn=print, minArgs=0, maxArgs=None),"jsonParse": STLFunction(fn=jsonParse, minArgs=1, maxArgs=1),- "jsonStringify": STLFunction(fn=jsonStringify, minArgs=1, maxArgs=1),+ "jsonStringify": STLFunction(fn=jsonStringify, minArgs=1, maxArgs=2),"JSONHas": STLFunction(fn=JSONHas, minArgs=2, maxArgs=None),"isValidJSON": STLFunction(fn=isValidJSON, minArgs=1, maxArgs=1),- "JSONLength": STLFunction(fn=JSONLength, minArgs=2, maxArgs=None),+ "JSONLength": STLFunction(fn=JSONLength, minArgs=1, maxArgs=None),"JSONExtractBool": STLFunction(fn=JSONExtractBool, minArgs=1, maxArgs=None),"base64Encode": STLFunction(fn=base64Encode, minArgs=1, maxArgs=1),"base64Decode": STLFunction(fn=base64Decode, minArgs=1, maxArgs=1),@@ -1133,7 +1133,9 @@ STL: dict[str, STLFunction] = {"toDateTime": STLFunction(fn=lambda args, team, stdout, timeout: toDateTime(args[0]), minArgs=1, maxArgs=2),"formatDateTime": STLFunction(fn=_formatDateTime, minArgs=2, maxArgs=3),"HogError": STLFunction(- fn=lambda args, team, stdout, timeout: new_hog_error(args[0], args[1], args[2] if len(args) > 2 else None),+ fn=lambda args, team, stdout, timeout: new_hog_error(+ args[0], args[1] if len(args) > 1 else None, args[2] if len(args) > 2 else None+ ),minArgs=1,maxArgs=3,),@@ -1145,13 +1147,15 @@ STL: dict[str, STLFunction] = {maxArgs=2,),"RetryError": STLFunction(- fn=lambda args, team, stdout, timeout: new_hog_error("RetryError", args[0], args[1] if len(args) > 1 else None),+ fn=lambda args, team, stdout, timeout: new_hog_error(+ "RetryError", args[0] if len(args) > 0 else None, args[1] if len(args) > 1 else None+ ),minArgs=0,maxArgs=2,),"NotImplementedError": STLFunction(fn=lambda args, team, stdout, timeout: new_hog_error(- "NotImplementedError", args[0], args[1] if len(args) > 1 else None+ "NotImplementedError", args[0] if len(args) > 0 else None, args[1] if len(args) > 1 else None),minArgs=0,maxArgs=2,@@ -1162,7 +1166,7 @@ STL: dict[str, STLFunction] = {"JSONExtractFloat": STLFunction(fn=JSONExtractFloat, minArgs=1),"JSONExtractInt": STLFunction(fn=JSONExtractInt, minArgs=1),"JSONExtractString": STLFunction(fn=JSONExtractString, minArgs=1),- "and": STLFunction(fn=and_fn, minArgs=2, maxArgs=2),+ "and": STLFunction(fn=and_fn, minArgs=1, maxArgs=None),"addDays": STLFunction(fn=addDays, minArgs=2, maxArgs=2),"assumeNotNull": STLFunction(fn=assumeNotNull, minArgs=1, maxArgs=1),"coalesce": STLFunction(fn=coalesce, minArgs=1, maxArgs=None),@@ -1184,7 +1188,7 @@ STL: dict[str, STLFunction] = {"multiIf": STLFunction(fn=multiIf, minArgs=3),"not": STLFunction(fn=not_fn, minArgs=1, maxArgs=1),"notEquals": STLFunction(fn=notEquals, minArgs=2, maxArgs=2),- "or": STLFunction(fn=or_fn, minArgs=2, maxArgs=2),+ "or": STLFunction(fn=or_fn, minArgs=1, maxArgs=None),"plus": STLFunction(fn=plus, minArgs=2, maxArgs=2),"range": STLFunction(fn=range_fn, minArgs=1, maxArgs=2),"round": STLFunction(fn=round_fn, minArgs=1, maxArgs=1),diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 00e60627d594..5883361cd677 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -16,7 +16,7 @@ from common.hogvm.python.operation import (HOGQL_BYTECODE_VERSION as VERSION,Operation as op,)-from common.hogvm.python.stl import sleep+from common.hogvm.python.stl import STL, sleepfrom common.hogvm.python.utils import HogVMException, UncaughtHogVMException@@ -163,6 +163,20 @@ class TestBytecodeExecute:try:execute_bytecode([_H, VERSION, op.CALL_GLOBAL, "replaceOne", 1], {})+ except Exception as e:+ assert str(e) == "Function replaceOne requires at least 3 arguments"+ else:+ raise AssertionError("Expected Exception not raised")++ try:+ execute_bytecode([_H, VERSION, op.STRING, "AB", op.STRING, "extra", op.CALL_GLOBAL, "lower", 2], {})+ except Exception as e:+ assert str(e) == "Function lower requires at most 1 arguments"+ else:+ raise AssertionError("Expected Exception not raised")++ try:+ execute_bytecode([_H, VERSION, op.CALL_GLOBAL, "lower", 1], {})except Exception as e:assert str(e) == "Stack underflow"else:@@ -175,6 +189,28 @@ class TestBytecodeExecute:else:raise AssertionError("Expected Exception not raised")+ def test_every_builtin_tolerates_its_own_min_args(self):+ # A builtin whose fn indexes past its declared minArgs raises a bare IndexError instead of a+ # HogVMException, which callers cannot tell apart from a bug in their own code. Blocking+ # builtins are excluded because calling them would sleep or shell out.+ leaked = []+ for name, stl_fn in STL.items():+ if stl_fn.is_blocking:+ continue+ arg_count = stl_fn.minArgs or 0+ bytecode: list[Any] = [_H, VERSION]+ for _ in range(arg_count):+ bytecode += [op.STRING, "1"]+ bytecode += [op.CALL_GLOBAL, name, arg_count]+ try:+ execute_bytecode(bytecode, {})+ except IndexError:+ leaked.append(name)+ except Exception:+ pass++ assert leaked == []+def test_memory_limits_1(self):# let string := 'banana'# for (let i := 0; i < 100; i := i + 1) {diff --git a/common/hogvm/typescript/package.json b/common/hogvm/typescript/package.jsonindex 73e8264ea771..4e6f399ee607 100644--- a/common/hogvm/typescript/package.json+++ b/common/hogvm/typescript/package.json@@ -1,6 +1,6 @@{"name": "@posthog/hogvm",- "version": "1.0.68",+ "version": "1.0.69","description": "PostHog Hog Virtual Machine","license": "MIT","author": "PostHog <[email protected]>",diff --git a/common/hogvm/typescript/src/__tests__/execute.test.ts b/common/hogvm/typescript/src/__tests__/execute.test.tsindex 4cda2c2ec2a2..7d0911c88ba5 100644--- a/common/hogvm/typescript/src/__tests__/execute.test.ts+++ b/common/hogvm/typescript/src/__tests__/execute.test.ts@@ -169,6 +169,13 @@ describe('hogvm execute', () => {expect(() => execSync(['_H', 1, op.CALL_GLOBAL, 'match', 1], options)).toThrow('Not enough arguments on the stack')++ expect(() => execSync(['_H', 1, op.STRING, 'a', op.CALL_GLOBAL, 'replaceOne', 1], options)).toThrow(+ 'Function replaceOne requires at least 3 arguments'+ )+ expect(() =>+ execSync(['_H', 1, op.STRING, 'AB', op.STRING, 'extra', op.CALL_GLOBAL, 'lower', 2], options)+ ).toThrow('Function lower requires at most 1 arguments')})test('null coercion in ordering comparisons - preserved behavior', () => {@@ -2027,7 +2034,7 @@ describe('hogvm execute', () => {test('uncaught exceptions', () => {// throw Error('Not a good day')- const bytecode1 = ['_h', op.NULL, op.NULL, op.STRING, 'Not a good day', op.CALL_GLOBAL, 'Error', 3, op.THROW]+ const bytecode1 = ['_h', op.STRING, 'Not a good day', op.CALL_GLOBAL, 'Error', 1, op.THROW]expect(() => execSync(bytecode1)).toThrow(new UncaughtHogVMException('Error', 'Not a good day', null))// throw RetryError('Not a good day', {'key': 'value'})diff --git a/common/hogvm/typescript/src/execute.ts b/common/hogvm/typescript/src/execute.tsindex dbeaa70c780f..540e9fdeea52 100644--- a/common/hogvm/typescript/src/execute.ts+++ b/common/hogvm/typescript/src/execute.ts@@ -853,13 +853,20 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):},} satisfies ExecResult} else if (Object.hasOwn(STL, name)) {+ const stlFn = STL[name]+ if (stlFn.minArgs !== undefined && temp < stlFn.minArgs) {+ throw new HogVMException(`Function ${name} requires at least ${stlFn.minArgs} arguments`)+ }+ if (stlFn.maxArgs !== undefined && temp > stlFn.maxArgs) {+ throw new HogVMException(`Function ${name} requires at most ${stlFn.maxArgs} arguments`)+ }const args =version === 0? Array(temp).fill(null).map(() => popStack()): stackKeepFirstElements(stack.length - temp)- pushStack(STL[name].fn(args, name, options))+ pushStack(stlFn.fn(args, name, options))} else if (Object.hasOwn(BYTECODE_STL, name)) {const argNames = BYTECODE_STL[name][0]if (argNames.length !== temp) {diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.tsindex 1665299406a2..9c61a79f65a1 100644--- a/common/hogvm/typescript/src/stl/stl.ts+++ b/common/hogvm/typescript/src/stl/stl.ts@@ -798,7 +798,7 @@ export const STL: Record<string, STLFunction> = {description: 'Converts an object to a JSON string',example: 'jsonStringify($1)',minArgs: 1,- maxArgs: 1,+ maxArgs: 2,},JSONHas: {fn: ([obj, ...path]) => {@@ -887,7 +887,7 @@ export const STL: Record<string, STLFunction> = {},description: 'Returns the length of a JSON array or object',example: 'JSONLength($1, $2)',- minArgs: 2,+ minArgs: 1,},JSONExtractBool: {fn: ([obj, ...path]) => {@@ -1653,15 +1653,13 @@ export const STL: Record<string, STLFunction> = {fn: andFn,description: 'Logical AND operation',example: 'and($1, $2)',- minArgs: 2,- maxArgs: 2,+ minArgs: 1,},or: {fn: orFn,description: 'Logical OR operation',example: 'or($1, $2)',- minArgs: 2,- maxArgs: 2,+ minArgs: 1,},plus: {fn: plusFn,diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.pyindex c0b77bc7c2d4..4b78c92f5751 100644--- a/posthog/temporal/ai_observability/evaluation_hog.py+++ b/posthog/temporal/ai_observability/evaluation_hog.py@@ -36,10 +36,11 @@ logger = structlog.get_logger(__name__)# - `ValueError` at large, with `json.JSONDecodeError` (a subclass) listed instead: our own code# raises plain ValueError, and skipping on that would hide real bugs.# - `IndexError`, which no user data reaches: Hog indexing is bounds-safe (`get_nested_value`-# returns null past the end of an array). What does raise it is an STL call compiled with the-# wrong arity, which nothing validates at save time, so a source like `jsonParse()` reaches the-# VM and fails on every unit. Listing it here would skip that source silently and forever, and-# blame the customer's data for it; left out, it stays loud.+# returns null past the end of an array), and the VM rejects a wrong-arity builtin at the dispatch+# site, so a source like `jsonParse()` raises HogVMException without reaching the STL function.+# Such a source fails on every unit, and `finalize_hog_eval_result` makes that a terminal+# hog_error which disables the evaluation. Neither error may count as an input error, or the+# broken source would skip every unit silently and blame the customer's data.HOG_INPUT_ERROR_TYPES: tuple[type[Exception], ...] = (TypeError,AttributeError,diff --git a/posthog/temporal/ai_observability/test_evaluation_hog.py b/posthog/temporal/ai_observability/test_evaluation_hog.pyindex e0c621d8e2cb..d00172613f74 100644--- a/posthog/temporal/ai_observability/test_evaluation_hog.py+++ b/posthog/temporal/ai_observability/test_evaluation_hog.py@@ -27,7 +27,8 @@ NON_BOOLEAN_SOURCE = """return 42"""-# Nothing validates builtin arity at save time, so this compiles and raises IndexError in the STL.+# A builtin called with the wrong argument count. The VM validates arity at the dispatch site, so+# this raises HogVMException rather than an IndexError from inside the STL function.MISSING_ARGUMENT_SOURCE = """return jsonParse()"""@@ -61,15 +62,21 @@ class TestHogInputErrorClassification:assert result["error"] is Noneassert result["verdict"] is False- # The exclusions from HOG_INPUT_ERROR_TYPES are invisible otherwise: widening the tuple back to- # Exception leaves every case above classifying identically, so only a case that must NOT be an- # input error can catch it. A source that fails on every unit has to stay loud, or it skips- # forever while blaming the customer's data.- def test_source_that_can_never_run_stays_our_bug(self) -> None:+ # A source that fails on every unit must not be classified as an input error, or it skips+ # forever while blaming the customer's data. A wrong-arity builtin is a broken source: the VM+ # raises HogVMException, which is neither an input error nor our bug. finalize_hog_eval_result+ # turns it into a terminal hog_error that disables the evaluation and tells the user, instead of+ # paging us once per unit.+ def test_wrong_arity_builtin_is_a_broken_source(self) -> None:result = run_source(MISSING_ARGUMENT_SOURCE)- assert result["unexpected"] is True+ assert result["error"] is not Noneassert "user_input_error" not in result+ assert "unexpected" not in result++ finalized = finalize_hog_eval_result(result, evaluation=EVALUATION, allows_na=True, unit_label=None)+ assert finalized["skip_reason"] == "hog_error"+ assert is_terminal_user_error_result(finalized) is Trueclass TestFinalizeHogEvalResult: