: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(hogql): share placeholder memory budgets (#102828)
Marius Andra074bf499717b
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.pyindex 792306ba34c5..6a7b514b4d63 100644--- a/common/hogvm/python/execute.py+++ b/common/hogvm/python/execute.py@@ -16,7 +16,7 @@ from common.hogvm.python.objects import (new_hog_closure,)from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, HOGQL_BYTECODE_IDENTIFIER_V0, Operation-from common.hogvm.python.stl import STL+from common.hogvm.python.stl import STL, STLFunctionfrom common.hogvm.python.stl.bytecode import BYTECODE_STLfrom common.hogvm.python.utils import (MAX_MEMORY,@@ -39,11 +39,12 @@ MAX_FUNCTION_ARGS_LENGTH = 300CALLSTACK_LENGTH = 1000-@dataclass+@dataclass(frozen=False)class BytecodeResult:result: Anybytecodes: dict[str, Any]stdout: list[str]+ max_memory_used: int = 0def _compare_values(left: Any, right: Any, comparison: Callable[[Any, Any], bool]) -> bool:@@ -61,6 +62,7 @@ def execute_bytecode(team: Optional["Team"] = None,debug=False,disallowed_functions: Optional[frozenset[str]] = None,+ memory_limit: int = MAX_MEMORY,) -> BytecodeResult:bytecodes: dict[str, Any] = input if isinstance(input, dict) else {"root": {"bytecode": input}}root_bytecode = bytecodes.get("root", {}).get("bytecode", []) or []@@ -72,7 +74,7 @@ def execute_bytecode():raise HogVMException(f"Invalid bytecode. Must start with '{HOGQL_BYTECODE_IDENTIFIER}'")version = root_bytecode[1] if len(root_bytecode) >= 2 and root_bytecode[0] == HOGQL_BYTECODE_IDENTIFIER else 0- start_time = time.time()+ start_time = time.monotonic()last_op = len(root_bytecode) - 1stack: list = []upvalues: list[dict] = []@@ -173,16 +175,25 @@ def execute_bytecode(mem_used += mem_stack[-1]nonlocal max_mem_usedmax_mem_used = max(mem_used, max_mem_used)- if mem_used > MAX_MEMORY:- raise HogVMMemoryExceededException(memory_limit=MAX_MEMORY, attempted_memory=mem_used)+ if mem_used > memory_limit:+ raise HogVMMemoryExceededException(memory_limit=memory_limit, attempted_memory=mem_used)def check_timeout():- if time.time() - start_time > timeout.total_seconds() and not debug:+ if time.monotonic() - start_time > timeout.total_seconds() and not debug:raise HogVMRuntimeExceededException(timeout_seconds=timeout.total_seconds(), ops_performed=ops)def remaining_timeout() -> float:# Budget left for this run, so blocking STL functions (e.g. sleep) can bound themselves to it.- return max(0.0, timeout.total_seconds() - (time.time() - start_time))+ return max(0.0, timeout.total_seconds() - (time.monotonic() - start_time))++ def call_stl(stl_fn: STLFunction, args: list[Any]) -> Any:+ if stl_fn.memory_cost is not None:+ attempted_memory = mem_used + stl_fn.memory_cost(args)+ if attempted_memory > memory_limit:+ raise HogVMMemoryExceededException(memory_limit=memory_limit, attempted_memory=attempted_memory)+ result = stl_fn.fn(args, team, stdout, remaining_timeout())+ check_timeout()+ return resultdef check_allowed(name: str):# Enforced at dispatch so it catches every path to an STL call (direct, expression call,@@ -217,8 +228,12 @@ def execute_bytecode(if len(call_stack) == 0 or last_call_frame is None:if len(stack) > 1:raise HogVMException("Invalid bytecode. More than one value left on stack")+ check_timeout()return BytecodeResult(- result=pop_stack() if len(stack) > 0 else None, stdout=stdout, bytecodes=bytecodes+ result=pop_stack() if len(stack) > 0 else None,+ stdout=stdout,+ bytecodes=bytecodes,+ max_memory_used=max_mem_used,)stack_start = last_call_frame.stack_startstack_keep_first_elements(stack_start)@@ -358,7 +373,10 @@ def execute_bytecode(response = pop_stack()last_call_frame = call_stack.pop()if len(call_stack) == 0 or last_call_frame is None:- return BytecodeResult(result=response, stdout=stdout, bytecodes=bytecodes)+ check_timeout()+ return BytecodeResult(+ result=response, stdout=stdout, bytecodes=bytecodes, max_memory_used=max_mem_used+ )stack_start = last_call_frame.stack_startstack_keep_first_elements(stack_start)push_stack(response)@@ -564,7 +582,7 @@ def execute_bytecode(args = [pop_stack() for _ in range(arg_count)]else:args = stack_keep_first_elements(len(stack) - arg_count)- push_stack(stl_fn.fn(args, team, stdout, remaining_timeout()))+ push_stack(call_stl(stl_fn, args))elif name in BYTECODE_STL:arg_names = BYTECODE_STL[name][0]if len(arg_names) != arg_count:@@ -641,7 +659,7 @@ def execute_bytecode(args = list(reversed([pop_stack() for _ in range(args_length)]))if stl_fn.maxArgs is not None and len(args) < stl_fn.maxArgs:args = [*args, *([None] * (stl_fn.maxArgs - len(args)))]- push_stack(stl_fn.fn(args, team, stdout, remaining_timeout()))+ push_stack(call_stl(stl_fn, args))elif callable.get("__hogCallable__") == "async":raise HogVMException("Async functions are not supported")@@ -691,7 +709,13 @@ def execute_bytecode(frame.ip += 1- return BytecodeResult(result=pop_stack() if len(stack) > 0 else None, stdout=stdout, bytecodes=bytecodes)+ check_timeout()+ return BytecodeResult(+ result=pop_stack() if len(stack) > 0 else None,+ stdout=stdout,+ bytecodes=bytecodes,+ max_memory_used=max_mem_used,+ )def validate_bytecode(bytecode: list[Any] | dict, inputs: Optional[dict] = None) -> tuple[bool, Optional[str]]:diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 9a9ea999e470..9c437ffedd77 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -44,7 +44,7 @@ if TYPE_CHECKING:from posthog.models import Team[email protected](frozen=False)class STLFunction:fn: Callable[[list[Any], Optional["Team"], list[str] | None, float], Any]minArgs: Optional[int] = None@@ -52,6 +52,7 @@ class STLFunction:# Blocks the thread on time or I/O the VM's cooperative timeout can't interrupt, so callers# that run untrusted Hog on a request thread (e.g. HogQL placeholders) must refuse it.is_blocking: bool = False+ memory_cost: Callable[[list[Any]], int] | None = Nonedef toString(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):@@ -878,6 +879,11 @@ def _guard_sequence_length(length: int) -> None:raise HogVMMemoryExceededException(memory_limit=MAX_MEMORY, attempted_memory=(length + 1) * COST_PER_UNIT)+def _range_memory_cost(args: list[Any]) -> int:+ length = args[0] if len(args) == 1 else args[1] - args[0]+ return (max(0, length) + 1) * COST_PER_UNIT++def range_fn(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> Any:# range(a,b) -> [a..b-1], range(x) -> [0..x-1]if len(args) == 1:@@ -1193,7 +1199,7 @@ STL: dict[str, STLFunction] = {"notEquals": STLFunction(fn=notEquals, 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),+ "range": STLFunction(fn=range_fn, minArgs=1, maxArgs=2, memory_cost=_range_memory_cost),"round": STLFunction(fn=round_fn, minArgs=1, maxArgs=2),"startsWith": STLFunction(fn=startsWith, minArgs=2, maxArgs=2),"substring": STLFunction(fn=substring, minArgs=2, maxArgs=3),diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 2fe21a6aef2e..4376a69b723f 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -1,6 +1,7 @@import jsonimport timefrom collections.abc import Callable+from datetime import timedeltafrom typing import Any, Optional, castimport pytest@@ -24,6 +25,7 @@ from common.hogvm.python.utils import (MAX_REGEX_PATTERN_LENGTH,HogVMException,HogVMMemoryExceededException,+ HogVMRuntimeExceededException,UncaughtHogVMException,)@@ -416,6 +418,33 @@ class TestBytecodeExecute:with pytest.raises(HogVMMemoryExceededException):_guard_sequence_length(_MAX_SEQUENCE_LENGTH + 1)+ @parameterized.expand([("range(0, 200)",), ("(range)(0, 200)",)])+ def test_range_checks_remaining_memory_before_allocating(self, expression: str) -> None:+ bytecode = create_bytecode(parse_program("let retained := '" + "x" * 1000 + "'; return " + expression)).bytecode+ with patch("common.hogvm.python.stl.list", side_effect=AssertionError("Allocated range"), create=True):+ with pytest.raises(HogVMMemoryExceededException):+ execute_bytecode(bytecode, memory_limit=2048)++ @parameterized.expand([("range(7)", 7), ("range(3, 10)", 7), ("range(-1)", 0), ("range(10, 3)", 0)])+ def test_range_within_memory_limit(self, expression: str, expected_length: int) -> None:+ bytecode = create_bytecode(parse_expr(expression)).bytecode+ response = execute_bytecode(bytecode, memory_limit=64)+ assert len(response.result) == expected_length++ @parameterized.expand([(op.RETURN,), (None,), ()])+ def test_peak_memory_includes_temporary_values(self, *ending: op | None) -> None:+ bytecode = [_H, VERSION, op.INTEGER, 7, op.CALL_GLOBAL, "range", 1, op.CALL_GLOBAL, "length", 1, *ending]+ response = execute_bytecode(bytecode, memory_limit=64)+ assert response.result == 7+ assert response.max_memory_used == 64++ @parameterized.expand([("length('hello')",), ("(length)('hello')",)])+ def test_stl_call_cannot_return_after_deadline(self, expression: str) -> None:+ bytecode = create_bytecode(parse_expr(expression)).bytecode+ with patch("common.hogvm.python.execute.time.monotonic", side_effect=[0.0, 0.0, 0.0, 2.0]):+ with pytest.raises(HogVMRuntimeExceededException):+ execute_bytecode(bytecode, timeout=timedelta(seconds=1))+def test_functions(self):def stringify(*args):if args[0] == 1:diff --git a/docs/published/handbook/engineering/databases/hogql-python.md b/docs/published/handbook/engineering/databases/hogql-python.mdindex 44e8a7e4a06e..0e048a855458 100644--- a/docs/published/handbook/engineering/databases/hogql-python.md+++ b/docs/published/handbook/engineering/databases/hogql-python.md@@ -47,6 +47,12 @@ Few things to note:- Placeholders like `{where}` are just nodes of type `ast.Placeholder(field='where')`. You can leave them in, and call `stmt = replace_placeholders(stmt, { where: parse_expr('1') })` later.- We wrote one AST node ourselves: `ast.Constant(value=num_last_days)`. We did it to sanitize the value by make sure it's treated as a constant. We might simplify constants further (e.g. `parse_const` or just `{days: 2}`), but we're not there yet.+Placeholder expansion allows at most 1,000 placeholders and shares a five-second deadline across the query.+All placeholders also share a 64 MiB budget in Hog VM memory units, charged using each expression's peak stack usage, including temporary values.+This accounting is not a limit on Python process memory.+The `range()` builtin checks its result size against the remaining VM allowance before allocating the list.+Queries that exceed these limits fail during expansion; reduce the number or size of the placeholder expressions to stay within them.+## Pattern matching during query preparationExpressions inside HogQL placeholders execute in the Python HogVM.diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.pyindex 4987941e4002..211b8ad13b8a 100644--- a/posthog/hogql/placeholders.py+++ b/posthog/hogql/placeholders.py@@ -8,6 +8,7 @@ from posthog.hogql.utils import deserialize_hx_ast, is_simple_valuefrom posthog.hogql.visitor import CloningVisitor, TraversingVisitorfrom common.hogvm.python.stl import BLOCKING_FUNCTIONS+from common.hogvm.python.utils import MAX_MEMORY# Placeholder expressions run through the Hog VM on the request thread. Bound the work per query,# not per expression: one deadline shared across all placeholders, and a cap on how many a single@@ -77,6 +78,7 @@ class ReplacePlaceholders(CloningVisitor):self.placeholders = placeholdersself._expansions = 0self._deadline: Optional[float] = None+ self._remaining_memory = MAX_MEMORYdef visit_placeholder(self, node):# avoid circular imports@@ -113,11 +115,17 @@ class ReplacePlaceholders(CloningVisitor):self.placeholders,timeout=timedelta(seconds=remaining),disallowed_functions=BLOCKING_FUNCTIONS,+ memory_limit=self._remaining_memory,)+ # Charge temporary values too, even when the placeholder returns only a scalar.+ self._remaining_memory -= response.max_memory_usedif isinstance(response.result, dict) and ("__hx_ast" in response.result or "__hx_tag" in response.result):response.result = deserialize_hx_ast(response.result)+ if time.monotonic() >= self._deadline:+ raise QueryError("Expanding this query's placeholders took too long. Simplify it and try again.")+if (isinstance(response.result, ast.Expr)or isinstance(response.result, ast.SelectQuery)diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.pyindex 6259b4244649..927e586ff0cf 100644--- a/posthog/hogql/test/test_placeholders.py+++ b/posthog/hogql/test/test_placeholders.py@@ -1,24 +1,25 @@-import timefrom datetime import timedelta+from itertools import countfrom typing import castfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.hogql import ast-from posthog.hogql.compiler.bytecode import create_bytecodefrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.placeholders import find_placeholders, replace_placeholdersfrom posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.visitor import clear_locations-from common.hogvm.python.utils import HogVMException+from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededException, HogVMRuntimeExceededException-class TestParser(BaseTest):+class TestParser(SimpleTestCase):def test_find_placeholders(self):expr = parse_expr("{foo} and {bar.bah}")self.assertEqual(sorted(find_placeholders(expr).placeholder_fields), sorted([["foo"], ["bar", "bah"]]))@@ -90,20 +91,29 @@ class TestParser(BaseTest):@patch("posthog.hogql.placeholders.PLACEHOLDER_EXPANSION_BUDGET", timedelta(seconds=0.01))def test_replace_placeholders_charges_compilation_to_the_time_budget(self):- # The VM starts its own clock when it is called, so a budget measured before compilation- # would hand it a full allowance on top of what compilation already spent.- real_create_bytecode = create_bytecode-- def slow_create_bytecode(*args, **kwargs):- time.sleep(0.05)- return real_create_bytecode(*args, **kwargs)-expr = ast.Placeholder(expr=ast.Constant(value=1))- with patch("posthog.hogql.compiler.bytecode.create_bytecode", slow_create_bytecode):+ with patch("posthog.hogql.placeholders.time.monotonic", side_effect=[0.0, 0.05]):with self.assertRaises(QueryError) as context:replace_placeholders(expr, {})self.assertIn("took too long", str(context.exception))+ @parameterized.expand([(100, "{length(range(7))}", 1), (16, "{1}", 2)])+ def test_replace_placeholders_shares_memory(self, budget: int, expression: str, allowed_count: int) -> None:+ allowed = parse_select("SELECT " + ", ".join([expression] * allowed_count))+ oversized = parse_select("SELECT " + ", ".join([expression] * (allowed_count + 1)))+ with patch("posthog.hogql.placeholders.MAX_MEMORY", budget):+ self.assertEqual(len(cast(ast.SelectQuery, replace_placeholders(allowed, {})).select), allowed_count)+ with self.assertRaises(HogVMMemoryExceededException):+ replace_placeholders(oversized, {})+ self.assertEqual(len(cast(ast.SelectQuery, replace_placeholders(allowed, {})).select), allowed_count)++ @patch("posthog.hogql.placeholders.PLACEHOLDER_EXPANSION_BUDGET", timedelta(seconds=1))+ def test_replace_placeholders_shares_deadline(self) -> None:+ query = parse_select("SELECT " + ", ".join(["{1}"] * 100))+ with patch("posthog.hogql.placeholders.time.monotonic", side_effect=count(0.0, 0.01)):+ with self.assertRaises((QueryError, HogVMRuntimeExceededException)):+ replace_placeholders(query, {})+def test_replace_placeholders_comparison(self):expr = clear_locations(parse_expr("timestamp < {timestamp}"))self.assertEqual(