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(error-tracking): extract exception array props for hasAny in HogQL (#68027)

posthog[bot]891bbd3c2512
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index 9194daa9a4a1..738cd1f91037 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -53,6 +53,19 @@ BREAKDOWN_VALUES_LIMIT = 25
BREAKDOWN_VALUES_LIMIT_FOR_COUNTRIES = 300
BREAKDOWN_VALUE_MAX_LENGTH = 400
+# Event properties that hold a JSON-encoded array of strings. When materialized they are stored
+# as a raw String column, so any array function (hasAny/hasAll/...) run against them must first
+# extract the array via JSONExtract(..., 'Array(String)'). See posthog/hogql/property.py and the
+# PropertySwapper transform, which both apply that wrapping.
+EXCEPTION_STRING_ARRAY_PROPERTIES = frozenset(
+ {
+ "$exception_types",
+ "$exception_values",
+ "$exception_sources",
+ "$exception_functions",
+ }
+)
+
type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake", "redshift"]
# All dialects that compile to an external SQL database queried directly (as opposed to
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index b1a9161a9738..b16ee1dd2a7f 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -42,6 +42,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.base import AST
+from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES
from posthog.hogql.database.models import BooleanDatabaseField
from posthog.hogql.database.schema.sessions_v3 import LAZY_SESSIONS_FIELDS
from posthog.hogql.errors import NotImplementedError, QueryError
@@ -1002,12 +1003,9 @@ def property_to_expr(
# Use the all_urls array field to filter for pages visited during recording.
all_urls_field = ast.Call(name="groupUniqArrayArray", args=[ast.Field(chain=["all_urls"])])
- is_exception_string_array_property = property.type == "event" and property.key in [
- "$exception_types",
- "$exception_values",
- "$exception_sources",
- "$exception_functions",
- ]
+ is_exception_string_array_property = (
+ property.type == "event" and property.key in EXCEPTION_STRING_ARRAY_PROPERTIES
+ )
if is_exception_string_array_property:
# if materialized these columns will be strings so we need to extract them
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.py
index e50f548ee8df..169f92def992 100644
--- a/posthog/hogql/transforms/property_types.py
+++ b/posthog/hogql/transforms/property_types.py
@@ -5,6 +5,7 @@ from django.db import models
from django.db.models.functions.comparison import Coalesce
from posthog.hogql import ast
+from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.models import BooleanDatabaseField, DateTimeDatabaseField, StringJSONDatabaseField
from posthog.hogql.database.s3_table import S3Table
@@ -228,6 +229,13 @@ class PropertySwapper(CloningVisitor):
# to Float, the raw String value has to flow through for the parser to work.
_STRING_INPUT_CONVERSIONS: set[str] = {"toFloatOrZero", "toIntOrZero", "toFloatOrDefault", "toIntOrDefault"}
+ # ClickHouse array-membership functions whose first argument must be an array. Users write these
+ # against exception properties (e.g. hasAny(properties.$exception_values, [...])), but those
+ # properties are stored as a raw JSON String once materialized, so the bare column read raises
+ # ILLEGAL_TYPE_OF_ARGUMENT. We extract the array via JSONExtract(..., 'Array(String)') — the same
+ # wrapping property_to_expr applies to typed exception filters.
+ _ARRAY_MEMBERSHIP_FUNCTIONS: set[str] = {"has", "hasAll", "hasAny", "hasSubstr"}
+
def __init__(
self,
timezone: str,
@@ -321,11 +329,58 @@ class PropertySwapper(CloningVisitor):
self._inside_call_depth += 1
try:
- return super().visit_call(node)
+ result = super().visit_call(node)
finally:
self._inside_call_depth -= 1
self._suppress_numeric_conversion = saved_suppress
+ return self._maybe_extract_exception_string_array(result)
+
+ def _maybe_extract_exception_string_array(self, node: ast.Expr) -> ast.Expr:
+ """Wrap a bare exception-array property passed to an array-membership function in
+ JSONExtract(..., 'Array(String)'), so it type-checks against its materialized String column.
+
+ Only bare property reads are wrapped: property_to_expr already emits its own JSONExtract for
+ typed filters, and a user who wrote the extract by hand passes a Call here — neither is a bare
+ Field, so neither gets double-wrapped.
+ """
+ if not isinstance(node, ast.Call) or node.name not in self._ARRAY_MEMBERSHIP_FUNCTIONS or not node.args:
+ return node
+ if not self._is_exception_string_array_field(node.args[0]):
+ return node
+ node.args[0] = self._extract_string_array(node.args[0])
+ return node
+
+ def _is_exception_string_array_field(self, expr: ast.Expr) -> bool:
+ if isinstance(expr, ast.Alias):
+ expr = expr.expr
+ if not isinstance(expr, ast.Field):
+ return False
+ type = expr.type
+ if not (isinstance(type, ast.PropertyType) and type.field_type.name == "properties" and len(type.chain) == 1):
+ return False
+ if str(type.chain[0]) not in EXCEPTION_STRING_ARRAY_PROPERTIES:
+ return False
+ table_type = type.field_type.table_type
+ if not isinstance(table_type, ast.BaseTableType):
+ return False
+ return isinstance(table_type.resolve_database_table(self.context), EventsTable)
+
+ @staticmethod
+ def _extract_string_array(field: ast.Expr) -> ast.Call:
+ return ast.Call(
+ name="JSONExtract",
+ args=[
+ ast.Call(name="ifNull", args=[field, ast.Constant(value="")]),
+ ast.Constant(value="Array(String)"),
+ ],
+ type=ast.CallType(
+ name="JSONExtract",
+ arg_types=[ast.StringType(nullable=True), ast.StringType()],
+ return_type=ast.ArrayType(item_type=ast.StringType()),
+ ),
+ )
+
def _try_rewrite_json_extract_to_mat_column(self, node: ast.Call) -> ast.Expr | None:
"""Rewrite safe direct JSON property extraction to avoid reading the raw JSON blob.
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index 16ef540b28a8..179a26b8e79b 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -691,6 +691,32 @@ class TestPropertyTypes(BaseTest):
printed = self._print_select("select toFloatOrZero(toString(properties.$screen_width)) from events")
assert "toFloat64OrZero(toString(accurateCastOrNull" in printed
+ @parameterized.expand(
+ [
+ ("has", "has(properties.$exception_values, 'x')"),
+ ("hasAny", "hasAny(properties.$exception_values, ['x'])"),
+ ("hasAll", "hasAll(properties.$exception_values, ['x'])"),
+ ]
+ )
+ def test_exception_array_property_extracted_for_array_membership_functions(self, fn_name: str, expr: str):
+ # $exception_* array properties are stored as a raw JSON String once materialized, so passing the
+ # bare column to an array function raises ILLEGAL_TYPE_OF_ARGUMENT. It must first be extracted to
+ # Array(String) — the same wrapping property_to_expr applies to typed exception filters.
+ with materialized("events", "$exception_values"):
+ printed = self._print_select(f"select uuid from events where {expr}")
+ # The membership function receives the property extracted to an array, not the bare String column.
+ # (The 'Array(String)' type literal is parameterized out by the printer, so match structure instead.)
+ assert f"{fn_name}(JSONExtract(ifNull(" in printed
+ assert "events.`mat_$exception_values`" in printed
+ assert f"{fn_name}(events.`mat_$exception_values`" not in printed
+
+ def test_non_exception_array_property_left_untouched(self):
+ # Only the known $exception_* array properties get the wrapping; an ordinary property passed to an
+ # array function must be left untouched so we don't change results elsewhere.
+ with materialized("events", "$browser"):
+ printed = self._print_select("select uuid from events where hasAny(properties.$browser, ['x'])")
+ assert "hasAny(JSONExtract(" not in printed
+
def _print_select(self, select: str) -> str:
expr = parse_select(select)
query, _ = prepare_and_print_ast(