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(llma): handle Hog eval VM user errors (#67110)

Radu Raicea105c93f989e3
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.py
index 87823efb2df8..0aafff0015c3 100644
--- a/common/hogvm/python/execute.py
+++ b/common/hogvm/python/execute.py
@@ -6,8 +6,6 @@ from dataclasses import dataclass
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional
-import re2
-
from common.hogvm.python.debugger import color_bytecode, debugger
from common.hogvm.python.objects import (
CallFrame,
@@ -21,7 +19,6 @@ from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, HOGQL_BYTEC
from common.hogvm.python.stl import STL
from common.hogvm.python.stl.bytecode import BYTECODE_STL
from common.hogvm.python.utils import (
- _CASE_INSENSITIVE_OPTS,
HogVMException,
HogVMMemoryExceededException,
HogVMRuntimeExceededException,
@@ -29,6 +26,7 @@ from common.hogvm.python.utils import (
calculate_cost,
get_nested_value,
like,
+ regex_match,
set_nested_value,
unify_comparison_types,
)
@@ -285,24 +283,16 @@ def execute_bytecode(
push_stack(pop_stack() not in pop_stack())
case Operation.REGEX:
args = [pop_stack(), pop_stack()]
- push_stack(bool(re2.search(re2.compile(args[1]), args[0])) if args[0] and args[1] else False)
+ push_stack(regex_match(args[0], args[1]))
case Operation.NOT_REGEX:
args = [pop_stack(), pop_stack()]
- push_stack(not bool(re2.search(re2.compile(args[1]), args[0])) if args[0] and args[1] else False)
+ push_stack(not regex_match(args[0], args[1]) if args[0] and args[1] else False)
case Operation.IREGEX:
args = [pop_stack(), pop_stack()]
- push_stack(
- bool(re2.search(re2.compile(args[1], options=_CASE_INSENSITIVE_OPTS), args[0]))
- if args[0] and args[1]
- else False
- )
+ push_stack(regex_match(args[0], args[1], case_insensitive=True))
case Operation.NOT_IREGEX:
args = [pop_stack(), pop_stack()]
- push_stack(
- not bool(re2.search(re2.compile(args[1], options=_CASE_INSENSITIVE_OPTS), args[0]))
- if args[0] and args[1]
- else False
- )
+ push_stack(not regex_match(args[0], args[1], case_insensitive=True) if args[0] and args[1] else False)
case Operation.GET_GLOBAL:
chain = [pop_stack() for _ in range(next_token())]
if chunk_globals and chain[0] in chunk_globals:
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.py
index 54f26e4407d4..e5a4b8621a47 100644
--- a/common/hogvm/python/stl/__init__.py
+++ b/common/hogvm/python/stl/__init__.py
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any, Optional
import pytz
from ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_error, to_hog_interval
-from ..utils import HogVMException, get_nested_value, like
+from ..utils import HogVMException, _require_string, get_nested_value, like
from .crypto import md5, sha256, sha256HmacChain
from .date import (
formatDateTime,
@@ -965,6 +965,17 @@ def extractRegex(args: list[Any], team: Optional["Team"], stdout: Optional[list[
return ""
+def match(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
+ if args[1] is None or args[0] is None:
+ return False
+ input_string = _require_string(args[0], "input", "match")
+ pattern = _require_string(args[1], "pattern", "match")
+ try:
+ return re.search(pattern, input_string) is not None
+ except re.error as e:
+ raise HogVMException(f"Invalid regex pattern: {e}") from e
+
+
STL: dict[str, STLFunction] = {
"concat": STLFunction(
fn=lambda args, team, stdout, timeout: "".join(
@@ -973,13 +984,7 @@ STL: dict[str, STLFunction] = {
minArgs=1,
maxArgs=None,
),
- "match": STLFunction(
- fn=lambda args, team, stdout, timeout: (
- False if args[1] is None or args[0] is None else bool(re.search(re.compile(args[1]), args[0]))
- ),
- minArgs=2,
- maxArgs=2,
- ),
+ "match": STLFunction(fn=match, minArgs=2, maxArgs=2),
"extractRegex": STLFunction(fn=extractRegex, minArgs=2, maxArgs=2),
"like": STLFunction(fn=lambda args, team, stdout, timeout: like(args[0], args[1]), minArgs=2, maxArgs=2),
"ilike": STLFunction(fn=lambda args, team, stdout, timeout: like(args[0], args[1], True), minArgs=2, maxArgs=2),
diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.py
index 1f37eeb2e0a1..15e436581b27 100644
--- a/common/hogvm/python/test/test_execute.py
+++ b/common/hogvm/python/test/test_execute.py
@@ -82,12 +82,16 @@ class TestBytecodeExecute:
assert self._run("match('test', 'e.*')") is True
assert self._run("match('test', '^e.*')") is False
assert self._run("match('test', 'x.*')") is False
+ assert self._run("match('test', '')") is True
+ assert self._run("match('', '')") is True
+ assert self._run("match('ab', '(?<=a)b')") is True
assert self._run("'test' =~ 'e.*'") is True
assert self._run("'test' !~ 'e.*'") is False
assert self._run("'test' =~ '^e.*'") is False
assert self._run("'test' !~ '^e.*'") is True
assert self._run("'test' =~ 'x.*'") is False
assert self._run("'test' !~ 'x.*'") is True
+ assert self._run("'' !~ 'x.*'") is False
assert self._run("'test' ~* 'EST'") is True
assert self._run("'test' =~* 'EST'") is True
assert self._run("'test' !~* 'EST'") is False
@@ -108,6 +112,28 @@ class TestBytecodeExecute:
with pytest.raises(HogVMException, match="'<=' not supported between instances of 'NoneType' and 'float'"):
self._run("properties.missing <= 1.0")
+ @parameterized.expand(
+ [
+ ("function_list_input", "match(['tool_call'], 'tool')", {}, "Function match requires input"),
+ ("function_invalid_pattern", "match('tool_call', '[')", {}, "Invalid regex pattern"),
+ ("operator_list_input", "['tool_call'] =~ 'tool'", {}, "Function match requires input"),
+ (
+ "operator_invalid_pattern",
+ "'tool_call' =~ properties.pattern",
+ {"pattern": "\\u"},
+ "Invalid regex pattern: invalid escape sequence: \\u",
+ ),
+ ]
+ )
+ def test_regex_errors_raise_hogvm_exception(self, _name, expr, properties, expected_message):
+ globals_dict = {"properties": properties}
+ bytecode = create_bytecode(parse_expr(expr)).bytecode
+
+ with pytest.raises(HogVMException) as exc_info:
+ execute_bytecode(bytecode, globals_dict)
+
+ assert expected_message in str(exc_info.value)
+
def test_nested_value(self):
my_dict = {
"properties": {
@@ -733,6 +759,9 @@ class TestBytecodeExecute:
else:
raise AssertionError("Expected Exception not raised")
+ with pytest.raises(HogVMException, match="Index 1 out of range for array of length 0"):
+ self._run_program("let calls := []; calls[1] := 'tool_call'; return true")
+
def test_bytecode_tuples(self):
# assert self._run_program("return (,);"), ()
assert self._run_program("return (1, 2, 3);") == (1, 2, 3)
diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.py
index 7fd7120ea21a..562f29ea31ea 100644
--- a/common/hogvm/python/utils.py
+++ b/common/hogvm/python/utils.py
@@ -46,7 +46,35 @@ class HogVMMemoryExceededException(HogVMException):
super().__init__(f"Memory limit of {memory_limit} bytes exceeded. Attempted to use {attempted_memory} bytes")
-def like(string, pattern, case_insensitive: bool = False):
+def _require_string(value: Any, name: str, function_name: str) -> str:
+ if not isinstance(value, str):
+ raise HogVMException(f"Function {function_name} requires {name} to be a string, got {type(value).__name__}")
+ return value
+
+
+def _format_regex_error(error: Exception) -> str:
+ if error.args and isinstance(error.args[0], bytes):
+ return error.args[0].decode("utf-8", errors="replace")
+ return str(error)
+
+
+def _compile_regex(pattern: str, case_insensitive: bool = False) -> Any:
+ try:
+ return re2.compile(pattern, options=_CASE_INSENSITIVE_OPTS) if case_insensitive else re2.compile(pattern)
+ except re2.error as e:
+ raise HogVMException(f"Invalid regex pattern: {_format_regex_error(e)}") from e
+
+
+def regex_match(string: Any, pattern: Any, case_insensitive: bool = False) -> bool:
+ if not string or not pattern:
+ return False
+
+ string = _require_string(string, "input", "match")
+ pattern = _require_string(pattern, "pattern", "match")
+ return _compile_regex(pattern, case_insensitive).search(string) is not None
+
+
+def like(string: Any, pattern: Any, case_insensitive: bool = False) -> bool:
pattern = re2.escape(pattern).replace("%", ".*").replace("_", ".")
re_pattern = re2.compile(pattern, options=_CASE_INSENSITIVE_OPTS) if case_insensitive else re2.compile(pattern)
return re_pattern.search(string) is not None
@@ -90,6 +118,8 @@ def set_nested_value(obj, chain, value) -> Any:
raise HogVMException(f"Invalid index: {chain[-1]}")
if chain[-1] <= 0:
raise HogVMException(f"Hog arrays start from index 1")
+ if chain[-1] > len(obj):
+ raise HogVMException(f"Index {chain[-1]} out of range for array of length {len(obj)}")
obj[chain[-1] - 1] = value
else:
raise HogVMException(f'Can not set property "{chain[-1]}" on object of type "{type(obj).__name__}"')
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 29bca74d94d4..8c283a25759c 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -1449,6 +1449,53 @@ class TestExecuteHogEvalActivity:
assert "Runtime error: '<=' not supported between instances of 'NoneType' and 'float'" in result["reasoning"]
assert "Unexpected error during evaluation" not in result["reasoning"]
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("source", "properties", "expected_reasoning"),
+ [
+ (
+ "return output =~ properties.pattern",
+ {"pattern": "\\u"},
+ "Invalid regex pattern",
+ ),
+ (
+ "return match(properties.tool_calls, 'tool')",
+ {"tool_calls": ["tool_call"]},
+ "Function match requires input",
+ ),
+ (
+ "let calls := []; calls[1] := 'tool_call'; return true",
+ {},
+ "Index 1 out of range",
+ ),
+ ],
+ ids=["invalid-regex", "list-regex-input", "array-assignment-index"],
+ )
+ async def test_hog_eval_vm_user_errors_return_skipped(self, source, properties, expected_reasoning):
+ from posthog.cdp.validation import compile_hog
+
+ bytecode = compile_hog(source, "destination")
+ evaluation = {
+ "id": "eval-id",
+ "name": "Hog Eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {"source": source, "bytecode": bytecode},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": 1,
+ }
+ event_properties = {"$ai_input": "test input", "$ai_output": "test output", **properties}
+
+ result = await execute_hog_eval_activity(evaluation, create_mock_event_data(1, properties=event_properties))
+
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "hog_error"
+ assert result["terminal_user_error"] is True
+ assert result["status_reason"] == "hog_error"
+ assert result["verdict"] is False
+ assert expected_reasoning in result["reasoning"]
+ assert "Unexpected error during evaluation" not in result["reasoning"]
+
@pytest.mark.asyncio
async def test_hog_eval_unexpected_error_raises(self):
from posthog.cdp.validation import compile_hog