: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): run match and extractRegex on re2 (#97597)
George Munyorobc908859fd6b
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 1857d58401b8..0a4d5a71ec5e 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, Optionalimport pytzfrom ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_error, to_hog_interval-from ..utils import HogVMException, _require_string, get_nested_value, like+from ..utils import HogVMException, _compile_regex, _require_string, get_nested_value, like, regex_extractfrom .crypto import md5, sha1, sha1HmacChain, sha256, sha256HmacChainfrom .date import (formatDateTime,@@ -273,7 +273,6 @@ def decodeURLComponent(args: list[Any], team: Optional["Team"], stdout: Optionaldef tryDecodeURLComponent(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> Optional[str]:- import reimport urllib.parses = args[0]@@ -947,37 +946,15 @@ def multiSearchAnyCaseInsensitive(args: list[Any], team, stdout, timeout):def extractRegex(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str:- """- Extract substring matching a regex pattern.- Matches ClickHouse extract(haystack, pattern) behavior:- - Returns first capture group if pattern has groups- - Returns whole match if no capture groups- - Returns empty string if no match- """- if args[0] is None or args[1] is None:- return ""- haystack = str(args[0])- pattern = str(args[1])- try:- match = re.search(pattern, haystack)- if not match:- return ""- if match.lastindex and match.lastindex >= 1:- return match.group(1) or ""- return match.group(0) or ""- except re.error:- return ""+ return regex_extract(args[0], args[1])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:+ if args[0] is None or args[1] is None:return Falseinput_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+ return _compile_regex(pattern).search(input_string) is not NoneSTL: dict[str, STLFunction] = {diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 98b0c96bec6b..db4be3efdaf9 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -1,4 +1,5 @@import json+import timefrom collections.abc import Callablefrom typing import Any, Optional, cast@@ -86,7 +87,6 @@ class TestBytecodeExecute:assert self._run("match('test', 'x.*')") is Falseassert self._run("match('test', '')") is Trueassert self._run("match('', '')") is True- assert self._run("match('ab', '(?<=a)b')") is Trueassert self._run("'test' =~ 'e.*'") is Trueassert self._run("'test' !~ 'e.*'") is Falseassert self._run("'test' =~ '^e.*'") is False@@ -118,6 +118,7 @@ class TestBytecodeExecute:[("function_list_input", "match(['tool_call'], 'tool')", {}, "Function match requires input"),("function_invalid_pattern", "match('tool_call', '[')", {}, "Invalid regex pattern"),+ ("function_lookbehind_unsupported", "match('ab', '(?<=a)b')", {}, "Invalid regex pattern"),("operator_list_input", "['tool_call'] =~ 'tool'", {}, "Function match requires input"),("operator_invalid_pattern",@@ -1204,10 +1205,45 @@ class TestBytecodeExecute:assert self._run("extractRegex(null, '\\\\w+')") == ""assert self._run("extractRegex('hello', null)") == ""+ # A pattern with a group that captured nothing still returns the group, not the whole match+ assert self._run("extractRegex('b', '(a)?b')") == ""+ assert self._run("extractRegex('b', '(?:(a)|b)')") == ""+# Complex pattern like ClickHouse sortableSemver usesassert self._run("extractRegex('v1.2.3-alpha', '(\\\\d+(\\\\.\\\\d+)+)')") == "1.2.3"assert self._run("extractRegex('version 10.20.30', '(\\\\d+(\\\\.\\\\d+)+)')") == "10.20.30"+ @parameterized.expand(+ [+ ("match", False),+ ("extractRegex", ""),+ ]+ )+ def test_regex_functions_run_in_linear_time(self, fn_name: str, expected: bool | str) -> None:+ # Python's re engine needs exponential time on this pattern, so this pins the engine choice.+ # CPU time rather than wall clock, so a paused runner cannot fail the assertion on its own.+ subject = "a" * 26 + "!"+ start = time.process_time()+ result = STL[fn_name].fn([subject, "(a+)+$"], None, None, 5.0)+ elapsed = time.process_time() - start+ assert result == expected+ assert elapsed < 1.0++ @parameterized.expand(+ [+ ("extractRegex", "café", r"\w+", "caf"),+ ("extractRegex", "日本語", r"\w+", ""),+ ("match", "Müller", r"^\w+$", False),+ ("match", "١٢٣", r"\d+", False),+ ]+ )+ def test_regex_character_classes_are_ascii_only(+ self, fn_name: str, subject: str, pattern: str, expected: bool | str+ ) -> None:+ # The linear-time test cannot pin this, because another linear-time engine could restore the+ # Unicode classes and still run fast. Python's re engine gives "café", a match, and true here.+ assert STL[fn_name].fn([subject, pattern], None, None, 5.0) == expected+def test_sortable_semver(self):# Basic semver parsingassert self._run("sortableSemver('1.2.3')") == [1, 2, 3]diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.pyindex e114498501dc..11822adec838 100644--- a/common/hogvm/python/utils.py+++ b/common/hogvm/python/utils.py@@ -71,6 +71,9 @@ def _format_regex_error(error: Exception) -> str:def _compile_regex(pattern: str, case_insensitive: bool = False) -> Any:+ # re2 matches in linear time, unlike Python's backtracking re engine. It also makes the character+ # classes ASCII-only, so `\w+` extracts "caf" from "café" and `^\w+$` does not match "Müller".+ # The =~ operator, like(), the Node VM and ClickHouse all use re2, so the Hog surfaces agree.try:return re2.compile(pattern, options=_CASE_INSENSITIVE_OPTS) if case_insensitive else re2.compile(pattern)except re2.error as e:@@ -86,6 +89,27 @@ def regex_match(string: Any, pattern: Any, case_insensitive: bool = False) -> boreturn _compile_regex(pattern, case_insensitive).search(string) is not None+def regex_extract(string: Any, pattern: Any) -> str:+ # Matches ClickHouse extract(): first capture group if the pattern has groups, else the whole+ # match, else empty.+ if string is None or pattern is None:+ return ""+ haystack = str(string)+ try:+ compiled = _compile_regex(str(pattern))+ except HogVMException:+ return ""+ found = compiled.search(haystack)+ if not found:+ return ""+ # Select on the pattern's static group count, not on which groups participated. A group that+ # captured nothing still wins over the whole match, so `(a)?b` on "b" gives "". The Node and+ # Rust VMs branch on the same static count.+ if compiled.groups > 0:+ return found.group(1) or ""+ return found.group(0) or ""++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)