: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 pattern matching inputs (#102827)
Marius Andra217df0cac8e1
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex ec03ff1dacd8..9a9ea999e470 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -18,6 +18,7 @@ from ..utils import (HogVMMemoryExceededException,_compile_regex,_require_string,+ _validate_regex_pattern,get_nested_value,like,regex_extract,@@ -978,6 +979,7 @@ def match(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],return Falseinput_string = _require_string(args[0], "input", "match")pattern = _require_string(args[1], "pattern", "match")+ _validate_regex_pattern(pattern)return _compile_regex(pattern).search(input_string) is not Nonediff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 47b53d80d052..2fe21a6aef2e 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -21,6 +21,7 @@ from common.hogvm.python.stl import _MAX_SEQUENCE_LENGTH, STL, _guard_sequence_lfrom common.hogvm.python.utils import (COST_PER_UNIT,MAX_MEMORY,+ MAX_REGEX_PATTERN_LENGTH,HogVMException,HogVMMemoryExceededException,UncaughtHogVMException,@@ -143,6 +144,49 @@ class TestBytecodeExecute:assert expected_message in str(exc_info.value)+ @pytest.mark.parametrize(+ "expression, expected",+ [+ ("match(input, pattern)", True),+ ("extractRegex(input, pattern)", "needle"),+ ("like(input, pattern)", True),+ ("ilike(input, pattern)", True),+ ("notLike(input, pattern)", False),+ ("notILike(input, pattern)", False),+ ("input like pattern", True),+ ("input ilike pattern", True),+ ("input not like pattern", False),+ ("input not ilike pattern", False),+ ("input =~ pattern", True),+ ("input !~ pattern", False),+ ("input =~* pattern", True),+ ("input !~* pattern", False),+ ],+ )+ @pytest.mark.parametrize("oversized_pattern", [False, True])+ def test_matching_accepts_large_subjects_but_bounds_patterns(+ self, expression: str, expected: bool | str, oversized_pattern: bool+ ) -> None:+ bytecode = create_bytecode(parse_expr(expression)).bytecode+ globals_dict = {+ "input": "z" * (8 * 1024 * 1024) + "needle",+ "pattern": "z" * (MAX_REGEX_PATTERN_LENGTH + 1) if oversized_pattern else "needle",+ }++ if oversized_pattern:+ with pytest.raises(HogVMException, match=f"exceeds {MAX_REGEX_PATTERN_LENGTH} characters"):+ execute_bytecode(bytecode, globals_dict, timeout=60)+ else:+ assert execute_bytecode(bytecode, globals_dict, timeout=60).result == expected++ @pytest.mark.parametrize("function_name", ["match", "extractRegex", "like", "ilike"])+ def test_regex_pattern_limit_is_inclusive(self, function_name: str) -> None:+ bytecode = create_bytecode(parse_expr(f"{function_name}(input, pattern)")).bytecode+ pattern = "z" * MAX_REGEX_PATTERN_LENGTH+ result = execute_bytecode(bytecode, {"input": "z", "pattern": pattern}, timeout=60).result++ assert result == ("" if function_name == "extractRegex" else False)+def test_nested_value(self):my_dict = {"properties": {diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.pyindex f045a1d6d6fc..99e2f5aea0f1 100644--- a/common/hogvm/python/utils.py+++ b/common/hogvm/python/utils.py@@ -10,6 +10,7 @@ _CASE_INSENSITIVE_OPTS.case_sensitive = FalseCOST_PER_UNIT = 8MAX_MEMORY = 64 * 1024 * 1024 # 64 MB+MAX_REGEX_PATTERN_LENGTH = 16 * 1024def _temporal_seconds(value: Any) -> float | None:@@ -71,6 +72,12 @@ def _format_regex_error(error: Exception) -> str:return str(error)+def _validate_regex_pattern(pattern: str) -> None:+ # Pattern compilation runs inside one opcode, before the VM can check its time budget again.+ if len(pattern) > MAX_REGEX_PATTERN_LENGTH:+ raise HogVMException(f"Pattern exceeds {MAX_REGEX_PATTERN_LENGTH} characters. Use a shorter pattern.")++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".@@ -87,6 +94,7 @@ def regex_match(string: Any, pattern: Any, case_insensitive: bool = False) -> bostring = _require_string(string, "input", "match")pattern = _require_string(pattern, "pattern", "match")+ _validate_regex_pattern(pattern)return _compile_regex(pattern, case_insensitive).search(string) is not None@@ -96,8 +104,10 @@ def regex_extract(string: Any, pattern: Any) -> str:if string is None or pattern is None:return ""haystack = str(string)+ pattern = str(pattern)+ _validate_regex_pattern(pattern)try:- compiled = _compile_regex(str(pattern))+ compiled = _compile_regex(pattern)except HogVMException:return ""found = compiled.search(haystack)@@ -112,6 +122,7 @@ def regex_extract(string: Any, pattern: Any) -> str:def like(string: Any, pattern: Any, case_insensitive: bool = False) -> bool:+ _validate_regex_pattern(pattern)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 Nonediff --git a/docs/published/handbook/engineering/databases/hogql-python.md b/docs/published/handbook/engineering/databases/hogql-python.mdindex 74cbab5e1af5..44e8a7e4a06e 100644--- a/docs/published/handbook/engineering/databases/hogql-python.md+++ b/docs/published/handbook/engineering/databases/hogql-python.md@@ -47,6 +47,18 @@ 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.+## Pattern matching during query preparation++Expressions inside HogQL placeholders execute in the Python HogVM.+Its regex and LIKE functions and operators accept patterns up to 16,384 characters.+Larger patterns raise a `HogVMException`; shorten the pattern before matching.+Subject strings have no separate matching limit and use the VM's existing 64 MiB stack memory budget, so matching can process multi-megabyte response bodies.+These limits also apply to `extractRegex`, which still returns an empty string for invalid regex syntax.+Regex matching uses RE2 syntax, so backreferences and lookaround are unsupported.++SQL LIKE and ILIKE patterns sent to ClickHouse are not subject to these VM limits.+For non-nullable materialized columns, patterns above 16,384 characters skip the optional sentinel-based rewrite and use the normal property read.+## AST nodesIf you want more control, you can build the AST nodes directly. The same query above can be written as:diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 6c41f2a93aa3..f08519598395 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -54,6 +54,7 @@ from posthog.schema_enums import MaterializationMode, PropertyGroupsMode# In non-nullable materialized columns these stored strings are treated as NULL.MAT_COL_NULL_SENTINELS = ["", "null"]+MAX_MATERIALIZED_LIKE_PATTERN_LENGTH = 16 * 1024# Leave the $ai_* bloom-filter columns to the printer: its comparison code already keeps them index-eligible# (`COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING`, imported above so the two lists stay in sync). The value-read side skips@@ -1754,6 +1755,9 @@ class ClickHousePropertyResolver(CloningVisitor):return _call("ifNull", [_call("notILike", [prop.bare_column(), _const(pattern.value)]), _const(True)])# Non-nullable: bail if the pattern could match a stored sentinel.+ # Skipping this optional rewrite bounds planning work without rejecting the query.+ if len(cast(str, pattern.value)) > MAX_MATERIALIZED_LIKE_PATTERN_LENGTH:+ return Noneif any(ilike_matches(cast(str, pattern.value), s) for s in MAT_COL_NULL_SENTINELS):return Noneif is_ilike:@@ -1776,6 +1780,8 @@ class ClickHousePropertyResolver(CloningVisitor):return _call("and", [_call("like", [prop.bare_column(), _const(pattern.value)]), prop.is_not_null()])return _call("ifNull", [_call("notLike", [prop.bare_column(), _const(pattern.value)]), _const(True)])+ if len(cast(str, pattern.value)) > MAX_MATERIALIZED_LIKE_PATTERN_LENGTH:+ return Noneif any(like_matches(cast(str, pattern.value), s) for s in MAT_COL_NULL_SENTINELS):return Noneif is_like:diff --git a/posthog/hogql/transforms/test/test_clickhouse_property_resolution.py b/posthog/hogql/transforms/test/test_clickhouse_property_resolution.pyindex 37e8f99d1c4b..86386280379b 100644--- a/posthog/hogql/transforms/test/test_clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/test/test_clickhouse_property_resolution.py@@ -8,8 +8,19 @@ from hypothesis import (settings as hypothesis_settings,strategies as st,)+from parameterized import parameterized-from posthog.hogql.transforms.clickhouse_property_resolution import _is_json_verbatim+from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.schema.events import EventsTable+from posthog.hogql.property_metadata import PropertyMetadata+from posthog.hogql.transforms.clickhouse_property_resolution import (+ MAX_MATERIALIZED_LIKE_PATTERN_LENGTH,+ _is_json_verbatim,+ clickhouse_property_resolution,+)++from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails# Plain text alone almost never lands in the accepted set, so bias half the draws to printable ASCII._PROPERTY_VALUES = st.one_of(@@ -32,3 +43,42 @@ class TestJSONVerbatimValues(SimpleTestCase):returnassert value in json.dumps({"key": value})assert value in json.dumps({"key": value}, ensure_ascii=False)+++class TestMaterializedLikePatternLimit(SimpleTestCase):+ @parameterized.expand(+ [(op, oversized) for op in ("Like", "NotLike", "ILike", "NotILike") for oversized in (False, True)]+ )+ def test_pattern_limit_preserves_property_read(self, op: str, oversized: bool) -> None:+ column = MaterializedColumn(+ name="mat_label",+ details=MaterializedColumnDetails(table_column="properties", property_name="label", is_disabled=False),+ is_nullable=False,+ )+ context = HogQLContext(+ use_new_events_schema=False,+ property_metadata=PropertyMetadata(+ materialized_columns=lambda: {"events": {("label", "properties"): column}}+ ),+ )+ field_type = ast.FieldType(name="properties", table_type=ast.TableType(table=EventsTable()))+ pattern = "z" * (MAX_MATERIALIZED_LIKE_PATTERN_LENGTH + int(oversized))+ comparison = ast.CompareOperation(+ op=ast.CompareOperationOp[op],+ left=ast.PropertyAccess(expr=ast.Field(chain=["properties"], type=field_type), keys=["label"]),+ right=ast.Constant(value=pattern),+ )++ result: ast.Expr = clickhouse_property_resolution(comparison, context)++ if oversized:+ assert isinstance(result, ast.CompareOperation)+ assert result.op == comparison.op+ assert result.right == ast.Constant(value=pattern)+ assert isinstance(result.left, ast.Call)+ assert result.left.name == "nullIf"+ else:+ assert isinstance(result, ast.Call)+ assert result.name == {"Like": "like", "NotLike": "notLike", "ILike": "ilike", "NotILike": "notILike"}[op]+ assert isinstance(result.args[0], ast.Field)+ assert result.args[0].chain[-1] == "mat_label"