: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): bound resource use in placeholder expansion (#97565)
George Munyoro9ee8902760fe
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.pyindex b26f1057122e..792306ba34c5 100644--- a/common/hogvm/python/execute.py+++ b/common/hogvm/python/execute.py@@ -19,6 +19,7 @@ from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, HOGQL_BYTECfrom common.hogvm.python.stl import STLfrom common.hogvm.python.stl.bytecode import BYTECODE_STLfrom common.hogvm.python.utils import (+ MAX_MEMORY,HogVMException,HogVMMemoryExceededException,HogVMRuntimeExceededException,@@ -34,7 +35,6 @@ from common.hogvm.python.utils import (if TYPE_CHECKING:from posthog.models import Team-MAX_MEMORY = 64 * 1024 * 1024 # 64 MBMAX_FUNCTION_ARGS_LENGTH = 300CALLSTACK_LENGTH = 1000diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 0a4d5a71ec5e..ec03ff1dacd8 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -11,7 +11,17 @@ from typing import TYPE_CHECKING, Any, Optionalimport pytzfrom ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_error, to_hog_interval-from ..utils import HogVMException, _compile_regex, _require_string, get_nested_value, like, regex_extract+from ..utils import (+ COST_PER_UNIT,+ MAX_MEMORY,+ HogVMException,+ HogVMMemoryExceededException,+ _compile_regex,+ _require_string,+ get_nested_value,+ like,+ regex_extract,+)from .crypto import md5, sha1, sha1HmacChain, sha256, sha256HmacChainfrom .date import (formatDateTime,@@ -855,11 +865,25 @@ def today(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],}+# The stack charges a value for memory when it is pushed, after it is built. Check the requested+# length up front so an oversized sequence is refused before it is built. The ceiling mirrors the+# stack's own accounting: a list of N elements costs (N + 1) * COST_PER_UNIT (one unit for the+# list itself), so the largest length the stack accepts is MAX_MEMORY // COST_PER_UNIT - 1.+_MAX_SEQUENCE_LENGTH = MAX_MEMORY // COST_PER_UNIT - 1+++def _guard_sequence_length(length: int) -> None:+ if length > _MAX_SEQUENCE_LENGTH:+ raise HogVMMemoryExceededException(memory_limit=MAX_MEMORY, attempted_memory=(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:+ _guard_sequence_length(args[0])return list(range(args[0]))elif len(args) == 2:+ _guard_sequence_length(args[1] - args[0])return list(range(args[0], args[1]))else:raise ValueError("range function supports 1 or 2 arguments only")diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex db4be3efdaf9..47b53d80d052 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -17,8 +17,14 @@ from common.hogvm.python.operation import (HOGQL_BYTECODE_VERSION as VERSION,Operation as op,)-from common.hogvm.python.stl import STL, sleep-from common.hogvm.python.utils import HogVMException, UncaughtHogVMException+from common.hogvm.python.stl import _MAX_SEQUENCE_LENGTH, STL, _guard_sequence_length, sleep+from common.hogvm.python.utils import (+ COST_PER_UNIT,+ MAX_MEMORY,+ HogVMException,+ HogVMMemoryExceededException,+ UncaughtHogVMException,+)class TestBytecodeExecute:@@ -350,6 +356,22 @@ class TestBytecodeExecute:else:raise AssertionError("Expected Exception not raised")+ def test_range_refuses_length_past_memory_ceiling(self):+ # The asserted size proves the guard fired before allocation, not after building the list.+ length = 10**12+ bytecode = [_H, VERSION, op.INTEGER, length, op.CALL_GLOBAL, "range", 1, op.RETURN]+ with pytest.raises(HogVMMemoryExceededException) as exc:+ execute_bytecode(bytecode, {})+ assert exc.value.attempted_memory == (length + 1) * COST_PER_UNIT++ def test_range_ceiling_matches_stack_accounting(self):+ # The ceiling is the largest length the stack accepts, so a list at the ceiling stays within+ # the limit and one past it is refused. Locks the boundary without allocating either list.+ assert (_MAX_SEQUENCE_LENGTH + 1) * COST_PER_UNIT <= MAX_MEMORY+ _guard_sequence_length(_MAX_SEQUENCE_LENGTH)+ with pytest.raises(HogVMMemoryExceededException):+ _guard_sequence_length(_MAX_SEQUENCE_LENGTH + 1)+def test_functions(self):def stringify(*args):if args[0] == 1:diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.pyindex 11822adec838..f045a1d6d6fc 100644--- a/common/hogvm/python/utils.py+++ b/common/hogvm/python/utils.py@@ -9,6 +9,7 @@ _CASE_INSENSITIVE_OPTS = re2.Options()_CASE_INSENSITIVE_OPTS.case_sensitive = FalseCOST_PER_UNIT = 8+MAX_MEMORY = 64 * 1024 * 1024 # 64 MBdef _temporal_seconds(value: Any) -> float | None:diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.pyindex 18c3b47d39ab..b2af55c40dfb 100644--- a/posthog/hogql/placeholders.py+++ b/posthog/hogql/placeholders.py@@ -1,3 +1,5 @@+import time+from datetime import timedeltafrom typing import Optionalfrom posthog.hogql import ast@@ -7,6 +9,12 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitorfrom common.hogvm.python.stl import BLOCKING_FUNCTIONS+# 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+# query may expand.+MAX_PLACEHOLDER_EXPANSIONS = 1000+PLACEHOLDER_EXPANSION_BUDGET = timedelta(seconds=5)+class FindBlockingCalls(TraversingVisitor):def __init__(self):@@ -62,6 +70,8 @@ class ReplacePlaceholders(CloningVisitor):def __init__(self, placeholders: Optional[dict[str, ast.Expr]]):super().__init__()self.placeholders = placeholders+ self._expansions = 0+ self._deadline: Optional[float] = Nonedef visit_placeholder(self, node):# avoid circular imports@@ -69,6 +79,13 @@ class ReplacePlaceholders(CloningVisitor):from common.hogvm.python.execute import execute_bytecode+ if self._deadline is None:+ self._deadline = time.monotonic() + PLACEHOLDER_EXPANSION_BUDGET.total_seconds()++ self._expansions += 1+ if self._expansions > MAX_PLACEHOLDER_EXPANSIONS:+ raise QueryError("This query has too many placeholder expressions to expand. Simplify it and try again.")+# This bytecode runs on the request thread before access control, so refuse blocking calls.# The static check gives a clear early error for the common `fn(...)` form; passing# disallowed_functions to the VM is the real guard, catching every indirect call path too.@@ -79,7 +96,19 @@ class ReplacePlaceholders(CloningVisitor):raise QueryError(f"Query placeholders can't use {disallowed}. Remove it and try again.")bytecode = create_bytecode(node.expr)- response = execute_bytecode(bytecode.bytecode, self.placeholders, disallowed_functions=BLOCKING_FUNCTIONS)++ # Measure after compiling: the traversal and compilation above run on the request thread+ # too, and the VM starts its own clock when called, so a stale value adds their cost on top.+ remaining = self._deadline - time.monotonic()+ if remaining <= 0:+ raise QueryError("Expanding this query's placeholders took too long. Simplify it and try again.")++ response = execute_bytecode(+ bytecode.bytecode,+ self.placeholders,+ timeout=timedelta(seconds=remaining),+ disallowed_functions=BLOCKING_FUNCTIONS,+ )if isinstance(response.result, dict) and ("__hx_ast" in response.result or "__hx_tag" in response.result):response.result = deserialize_hx_ast(response.result)diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.pyindex 7041a09e3b94..84e983704c15 100644--- a/posthog/hogql/test/test_placeholders.py+++ b/posthog/hogql/test/test_placeholders.py@@ -1,10 +1,14 @@+import time+from datetime import timedeltafrom typing import castfrom posthog.test.base import BaseTest+from unittest.mock import patchfrom 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_placeholders@@ -64,6 +68,34 @@ class TestParser(BaseTest):str(context.exception),)+ @patch("posthog.hogql.placeholders.MAX_PLACEHOLDER_EXPANSIONS", 3)+ def test_replace_placeholders_caps_expansion_count(self):+ # A low cap keeps the case away from the shared time budget: at the cap it resolves, one past+ # it is rejected.+ at_cap = ast.Array(exprs=[ast.Placeholder(expr=ast.Constant(value=1)) for _ in range(3)])+ resolved = replace_placeholders(at_cap, {})+ self.assertEqual(len(cast(ast.Array, resolved).exprs), 3)++ over_cap = ast.Array(exprs=[ast.Placeholder(expr=ast.Constant(value=1)) for _ in range(4)])+ with self.assertRaises(QueryError):+ replace_placeholders(over_cap, {})++ @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 self.assertRaises(QueryError) as context:+ replace_placeholders(expr, {})+ self.assertIn("took too long", str(context.exception))+def test_replace_placeholders_comparison(self):expr = clear_locations(parse_expr("timestamp < {timestamp}"))self.assertEqual(diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex f74a94883167..6cf3d456a0aa 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -130,7 +130,6 @@ posthog/hogql/test/test_escape_sql.py::TestPrintStringposthog/hogql/test/test_hogqlx.py::TestHogQLXposthog/hogql/test/test_log_query_settings.py::TestTooManyBytesErrorposthog/hogql/test/test_parser_cache.py::TestParserCache-posthog/hogql/test/test_placeholders.py::TestParserposthog/hogql/test/test_timings.py::TestHogQLTimingsposthog/hogql/test/test_utils.py::TestUtilsposthog/hogql/test/test_visitor.py::TestVisitor