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.

fix(hogql): stop blocking STL calls in query placeholders (#73955)

George Munyorobe546743bddb
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.py
index 0aafff0015c3..5cbf21a8e20b 100644
--- a/common/hogvm/python/execute.py
+++ b/common/hogvm/python/execute.py
@@ -60,6 +60,7 @@ def execute_bytecode(
timeout=timedelta(seconds=5),
team: Optional["Team"] = None,
debug=False,
+ disallowed_functions: Optional[frozenset[str]] = None,
) -> BytecodeResult:
bytecodes: dict[str, Any] = input if isinstance(input, dict) else {"root": {"bytecode": input}}
root_bytecode = bytecodes.get("root", {}).get("bytecode", []) or []
@@ -87,6 +88,7 @@ def execute_bytecode(
debug_bytecode = []
if isinstance(timeout, int):
timeout = timedelta(seconds=timeout)
+ disallowed_functions = disallowed_functions or frozenset()
if len(call_stack) == 0:
call_stack.append(
@@ -178,6 +180,16 @@ def execute_bytecode(
if time.time() - 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))
+
+ def check_allowed(name: str):
+ # Enforced at dispatch so it catches every path to an STL call (direct, expression call,
+ # a closure bound to a local), not just the syntactic `name(...)` a static check would see.
+ if name in disallowed_functions:
+ raise HogVMException(f"Function {name} is not allowed here")
+
def capture_upvalue(index) -> dict:
nonlocal upvalues
for upvalue in reversed(upvalues):
@@ -542,11 +554,12 @@ def execute_bytecode(
args = stack_keep_first_elements(len(stack) - arg_count)
push_stack(functions[name](*args))
elif name in STL:
+ check_allowed(name)
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, timeout.total_seconds()))
+ push_stack(STL[name].fn(args, team, stdout, remaining_timeout()))
elif name in BYTECODE_STL:
arg_names = BYTECODE_STL[name][0]
if len(arg_names) != arg_count:
@@ -609,6 +622,7 @@ def execute_bytecode(
elif callable.get("__hogCallable__") == "stl":
if callable["name"] not in STL:
raise HogVMException(f"Unsupported function call: {callable['name']}")
+ check_allowed(callable["name"])
stl_fn = STL[callable["name"]]
if stl_fn.minArgs is not None and args_length < stl_fn.minArgs:
raise HogVMException(
@@ -622,7 +636,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, timeout.total_seconds()))
+ push_stack(stl_fn.fn(args, team, stdout, remaining_timeout()))
elif callable.get("__hogCallable__") == "async":
raise HogVMException("Async functions are not supported")
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.py
index e5a4b8621a47..3d65dd791328 100644
--- a/common/hogvm/python/stl/__init__.py
+++ b/common/hogvm/python/stl/__init__.py
@@ -38,6 +38,9 @@ class STLFunction:
fn: Callable[[list[Any], Optional["Team"], list[str] | None, float], Any]
minArgs: Optional[int] = None
maxArgs: Optional[int] = None
+ # 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
def toString(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):
@@ -116,7 +119,8 @@ def length(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],
def sleep(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):
- time.sleep(args[0])
+ # Clamp to the VM's remaining budget (`timeout`) so a script can't pin the thread past its cap.
+ time.sleep(max(0.0, min(args[0], timeout)))
return None
@@ -1183,11 +1187,13 @@ STL: dict[str, STLFunction] = {
"toYear": STLFunction(fn=toYear, minArgs=1, maxArgs=1),
"today": STLFunction(fn=today, minArgs=0, maxArgs=0),
# only in python, async function in nodejs
- "sleep": STLFunction(fn=sleep, minArgs=1, maxArgs=1),
- "run": STLFunction(fn=run, minArgs=1, maxArgs=1),
+ "sleep": STLFunction(fn=sleep, minArgs=1, maxArgs=1, is_blocking=True),
+ "run": STLFunction(fn=run, minArgs=1, maxArgs=1, is_blocking=True),
"multiSearchAnyCaseInsensitive": STLFunction(
fn=multiSearchAnyCaseInsensitive,
minArgs=2,
maxArgs=2,
),
}
+
+BLOCKING_FUNCTIONS: frozenset[str] = frozenset(name for name, spec in STL.items() if spec.is_blocking)
diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.py
index 15e436581b27..00e60627d594 100644
--- a/common/hogvm/python/test/test_execute.py
+++ b/common/hogvm/python/test/test_execute.py
@@ -3,6 +3,7 @@ from collections.abc import Callable
from typing import Any, Optional, cast
import pytest
+from unittest.mock import patch
from parameterized import parameterized
@@ -15,6 +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.utils import HogVMException, UncaughtHogVMException
@@ -704,6 +706,30 @@ class TestBytecodeExecute:
with pytest.raises(HogVMException, match="Can not call length on null"):
self._run_program("return length(null);")
+ @parameterized.expand(
+ [
+ ("arg_over_budget_clamped_to_budget", 600.0, 0.5, 0.5),
+ ("arg_under_budget_left_as_is", 0.1, 5.0, 0.1),
+ ("negative_arg_clamped_to_zero", -5.0, 5.0, 0.0),
+ ]
+ )
+ def test_sleep_bounds_duration_to_remaining_timeout(self, _name, arg, budget, expected):
+ with patch("common.hogvm.python.stl.time.sleep") as mock_sleep:
+ sleep([arg], None, None, budget)
+ mock_sleep.assert_called_once_with(expected)
+
+ @parameterized.expand(
+ [
+ ("direct_call", "sleep(0)"), # CALL_GLOBAL dispatch
+ ("expression_call", "(sleep)(0)"), # CALL_LOCAL closure dispatch
+ ]
+ )
+ def test_disallowed_functions_rejected_at_dispatch(self, _name, expr):
+ bytecode = create_bytecode(parse_expr(expr)).bytecode
+ execute_bytecode(bytecode, {}) # allowed by default (sleeps 0s)
+ with pytest.raises(HogVMException, match="Function sleep is not allowed here"):
+ execute_bytecode(bytecode, {}, disallowed_functions=frozenset({"sleep"}))
+
def test_random_float(self):
for _ in range(50):
value = self._run_program("return randomFloat();")
diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.py
index 2daee0573138..f2b244453b00 100644
--- a/posthog/hogql/placeholders.py
+++ b/posthog/hogql/placeholders.py
@@ -5,6 +5,19 @@ from posthog.hogql.errors import QueryError
from posthog.hogql.utils import deserialize_hx_ast, is_simple_value
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
+from common.hogvm.python.stl import BLOCKING_FUNCTIONS
+
+
+class FindBlockingCalls(TraversingVisitor):
+ def __init__(self):
+ super().__init__()
+ self.names: set[str] = set()
+
+ def visit_call(self, node: ast.Call):
+ if node.name in BLOCKING_FUNCTIONS:
+ self.names.add(node.name)
+ super().visit_call(node)
+
class FindPlaceholders(TraversingVisitor):
def __init__(self):
@@ -43,8 +56,17 @@ class ReplacePlaceholders(CloningVisitor):
from common.hogvm.python.execute import execute_bytecode
+ # 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.
+ finder = FindBlockingCalls()
+ finder.visit(node.expr)
+ if finder.names:
+ disallowed = ", ".join(sorted(finder.names))
+ 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)
+ response = execute_bytecode(bytecode.bytecode, self.placeholders, 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.py
index 6ec3b8bac605..5786250cb9c4 100644
--- a/posthog/hogql/test/test_placeholders.py
+++ b/posthog/hogql/test/test_placeholders.py
@@ -2,7 +2,10 @@ from typing import cast
from posthog.test.base import BaseTest
+from parameterized import parameterized
+
from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.placeholders import find_placeholders, replace_placeholders
from posthog.hogql.printer import to_printed_hogql
@@ -202,3 +205,21 @@ class TestBytecodePlaceholders(BaseTest):
finder = find_placeholders(expr)
self.assertTrue(len(finder.placeholder_expressions) > 0)
self.assertEqual(finder.placeholder_fields, [])
+
+ @parameterized.expand(
+ [
+ ("sleep_direct", "{sleep(600)}", "sleep"),
+ ("run_direct", "{run('SELECT 1')}", "run"),
+ ("nested_in_another_call", "{concat(sleep(600))}", "sleep"),
+ # Indirect invocations bypass the static name check but must still be rejected at VM
+ # dispatch, otherwise the blocking function runs on the request thread.
+ ("sleep_expression_call", "{(sleep)(600)}", "sleep"),
+ ("run_expression_call", "{(run)('SELECT 1')}", "run"),
+ ("sleep_bound_to_local", "{(() -> {let f := sleep; return f(600)})()}", "sleep"),
+ ]
+ )
+ def test_replace_placeholders_rejects_blocking_functions(self, _name, query, fn_name):
+ expr = parse_expr(query)
+ with self.assertRaises((QueryError, HogVMException)) as context:
+ replace_placeholders(expr, {})
+ self.assertIn(fn_name, str(context.exception))