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(insights): validate UUID values in person ID and event UUID filters (#72492)

Thomas Obermüller57c76abd4f41
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.py
index 3a8af16c6676..947aac3dbcf6 100644
--- a/ee/clickhouse/test/test_error.py
+++ b/ee/clickhouse/test/test_error.py
@@ -124,6 +124,16 @@ from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error
467,
"CHQueryErrorCannotParseBool",
),
+ (
+ ServerException(
+ "Code: 376. DB::Exception: Cannot parse uuid 2026072018044213140: while converting '2026072018044213140' to UUID: while executing function equals. Stack trace:\n\n0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x00000000141cccd0",
+ code=376,
+ ),
+ "CHQueryErrorCannotParseUuid",
+ "Cannot parse uuid 2026072018044213140: while converting '2026072018044213140' to UUID: while executing function equals.",
+ 376,
+ "CHQueryErrorCannotParseUuid",
+ ),
(
ServerException(
"Code: 43. DB::Exception: Illegal type String of argument of function toInt64.",
diff --git a/posthog/errors.py b/posthog/errors.py
index 804ee05bca4c..bb3d8b9612ff 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -272,7 +272,7 @@ class CHQueryErrorTooManyBytes(ExposedCHQueryError):
pass
-class CHQueryErrorCannotParseUuid(InternalCHQueryError):
+class CHQueryErrorCannotParseUuid(ExposedCHQueryError):
pass
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.py
index 69539c475a39..44fd0ae244c0 100644
--- a/posthog/hogql/autocomplete.py
+++ b/posthog/hogql/autocomplete.py
@@ -31,6 +31,7 @@ from posthog.hogql.database.models import (
StringDatabaseField,
StringJSONDatabaseField,
Table,
+ UUIDDatabaseField,
VirtualTable,
)
from posthog.hogql.database.schema.events import EventsGroupSubTable, EventsPersonSubTable, EventsTable
@@ -192,6 +193,8 @@ def convert_field_or_table_to_type_string(
return "Float"
if isinstance(field_or_table, StringDatabaseField):
return "String"
+ if isinstance(field_or_table, UUIDDatabaseField):
+ return "String"
if isinstance(field_or_table, DateTimeDatabaseField):
return "DateTime"
if isinstance(field_or_table, DateDatabaseField):
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 12ff9e190f15..062c215ff99b 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1547,7 +1547,7 @@ class Database(BaseModel):
events_table.fields["person_id"] = FieldTraverser(chain=["pdi", "person_id"])
elif modifiers.personsOnEventsMode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- events_table.fields["person_id"] = StringDatabaseField(name="person_id")
+ events_table.fields["person_id"] = UUIDDatabaseField(name="person_id")
_use_person_properties_from_events(database)
elif modifiers.personsOnEventsMode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
@@ -2127,7 +2127,7 @@ def _use_person_properties_from_events(database: Database) -> None:
def _use_person_id_from_person_overrides(database: Database) -> None:
table = database.get_table("events")
- table.fields["event_person_id"] = StringDatabaseField(name="person_id")
+ table.fields["event_person_id"] = UUIDDatabaseField(name="person_id")
table.fields["override"] = LazyJoin(
from_field=["distinct_id"],
join_table=database.get_table("person_distinct_id_overrides"),
diff --git a/posthog/hogql/database/schema/events.py b/posthog/hogql/database/schema/events.py
index f11f34f044f8..529115782043 100644
--- a/posthog/hogql/database/schema/events.py
+++ b/posthog/hogql/database/schema/events.py
@@ -15,6 +15,7 @@ from posthog.hogql.database.models import (
StringDatabaseField,
StringJSONDatabaseField,
Table,
+ UUIDDatabaseField,
VirtualTable,
)
from posthog.hogql.database.schema.groups import GroupsTable
@@ -31,7 +32,7 @@ def events_table_clickhouse_table_ref(context) -> str:
class EventsPersonSubTable(VirtualTable):
fields: dict[str, FieldOrTable] = {
- "id": StringDatabaseField(name="person_id", nullable=False),
+ "id": UUIDDatabaseField(name="person_id", nullable=False),
"created_at": DateTimeDatabaseField(name="person_created_at", nullable=False),
"properties": StringJSONDatabaseField(name="person_properties", nullable=False),
"revenue_analytics": LazyJoin(
@@ -87,7 +88,7 @@ class EventsGroupSubTable(VirtualTable):
class EventsTable(Table):
description: str = "Every analytics event captured for the project. The central fact table for product analytics."
fields: dict[str, FieldOrTable] = {
- "uuid": StringDatabaseField(name="uuid", nullable=False, description="Unique identifier of this event row."),
+ "uuid": UUIDDatabaseField(name="uuid", nullable=False, description="Unique identifier of this event row."),
"event": StringDatabaseField(
name="event",
nullable=False,
diff --git a/posthog/hogql/database/schema/person_distinct_id_overrides.py b/posthog/hogql/database/schema/person_distinct_id_overrides.py
index 7190a10cc0ab..fbf05339731d 100644
--- a/posthog/hogql/database/schema/person_distinct_id_overrides.py
+++ b/posthog/hogql/database/schema/person_distinct_id_overrides.py
@@ -13,6 +13,7 @@ from posthog.hogql.database.models import (
LazyTableToAdd,
StringDatabaseField,
Table,
+ UUIDDatabaseField,
)
from posthog.hogql.errors import ResolutionError
@@ -23,7 +24,7 @@ PERSON_DISTINCT_ID_OVERRIDES_FIELDS: dict[str, FieldOrTable] = {
nullable=False,
description="Distinct_id whose person mapping was overridden (e.g. after an identify or merge).",
),
- "person_id": StringDatabaseField(
+ "person_id": UUIDDatabaseField(
name="person_id",
nullable=False,
description="Corrected person this distinct_id now resolves to; matches `persons.id`.",
diff --git a/posthog/hogql/database/schema/person_distinct_ids.py b/posthog/hogql/database/schema/person_distinct_ids.py
index 6f57757ae091..f13d88cd8020 100644
--- a/posthog/hogql/database/schema/person_distinct_ids.py
+++ b/posthog/hogql/database/schema/person_distinct_ids.py
@@ -13,6 +13,7 @@ from posthog.hogql.database.models import (
LazyTableToAdd,
StringDatabaseField,
Table,
+ UUIDDatabaseField,
)
from posthog.hogql.errors import ResolutionError
@@ -23,7 +24,7 @@ PERSON_DISTINCT_IDS_FIELDS: dict[str, FieldOrTable] = {
nullable=False,
description="Client-side distinct_id sent with events; multiple distinct_ids can map to one person.",
),
- "person_id": StringDatabaseField(
+ "person_id": UUIDDatabaseField(
name="person_id",
nullable=False,
description="Resolved person this distinct_id belongs to; matches `persons.id`.",
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.py
index 6bc207435cc3..d5f6c0278e9e 100644
--- a/posthog/hogql/database/schema/persons.py
+++ b/posthog/hogql/database/schema/persons.py
@@ -18,9 +18,9 @@ from posthog.hogql.database.models import (
LazyJoinToAdd,
LazyTable,
LazyTableToAdd,
- StringDatabaseField,
StringJSONDatabaseField,
Table,
+ UUIDDatabaseField,
)
from posthog.hogql.database.schema.persons_pdi import PersonsPDITable
from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
@@ -35,7 +35,7 @@ if TYPE_CHECKING:
from posthog.models.organization import Organization
PERSONS_FIELDS: dict[str, FieldOrTable] = {
- "id": StringDatabaseField(
+ "id": UUIDDatabaseField(
name="id", nullable=False, description="Stable person identifier; join target for `events.person_id`."
),
"created_at": DateTimeDatabaseField(
diff --git a/posthog/hogql/database/schema/persons_pdi.py b/posthog/hogql/database/schema/persons_pdi.py
index 6d1ad4381a02..572ec9f99d17 100644
--- a/posthog/hogql/database/schema/persons_pdi.py
+++ b/posthog/hogql/database/schema/persons_pdi.py
@@ -13,6 +13,7 @@ from posthog.hogql.database.models import (
LazyTable,
LazyTableToAdd,
StringDatabaseField,
+ UUIDDatabaseField,
)
from posthog.hogql.errors import ResolutionError
@@ -100,7 +101,7 @@ class PersonsPDITable(LazyTable):
nullable=False,
description="Client-side distinct_id sent with events; maps to a single person_id.",
),
- "person_id": StringDatabaseField(
+ "person_id": UUIDDatabaseField(
name="person_id",
nullable=False,
description="Resolved person this distinct_id belongs to; matches `persons.id`.",
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index 42f1abdc8a7c..0675ac5ccbf7 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -243,7 +243,7 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("person_id", "String"),
+ ("person_id", "UUID"),
("event_issue_id", "UUID"),
("issue_first_seen", "DateTime"),
("$virt_is_bot", "Boolean"),
@@ -272,7 +272,7 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
team=self.team,
)
columns = {row[0]: (row[1], row[2], row[3], row[4]) for row in response.results or []}
- assert columns["uuid"][0] == "String"
+ assert columns["uuid"][0] == "UUID"
assert columns["timestamp"][0] == "DateTime"
assert columns["properties"][0] == "JSON"
# `event` is a non-nullable string column
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index f569f7b5b551..20f703707792 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -1,3 +1,4 @@
+import re
from collections.abc import Callable
from datetime import date, datetime
from typing import Any, Optional, cast
@@ -71,6 +72,28 @@ USE_GLOBAL_JOINS = False
_SAFE_TABLE_FUNCTION_NAME_RE = re2.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+# ClickHouse's canonical UUID text form; it rejects anything else when parsing a compared literal.
+# Checked with fullmatch — a `$` anchor would let a trailing newline through.
+_UUID_LITERAL_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
+
+_UUID_GUARDED_COMPARE_OPS = (
+ ast.CompareOperationOp.Eq,
+ ast.CompareOperationOp.NotEq,
+ ast.CompareOperationOp.In,
+ ast.CompareOperationOp.NotIn,
+ ast.CompareOperationOp.GlobalIn,
+ ast.CompareOperationOp.GlobalNotIn,
+)
+
+
+def _string_constants(node: ast.Expr) -> list[ast.Constant]:
+ if isinstance(node, ast.Constant):
+ return [node] if isinstance(node.value, str) else []
+ if isinstance(node, (ast.Tuple, ast.Array)):
+ return [expr for expr in node.exprs if isinstance(expr, ast.Constant) and isinstance(expr.value, str)]
+ return []
+
+
EMPTY_SCOPE = ast.SelectQueryType()
type PostgresKeywordType = type[ast.DateType] | type[ast.DateTimeType]
@@ -2252,6 +2275,7 @@ class Resolver(CloningVisitor):
node = super().visit_compare_operation(node)
node.type = ast.BooleanType(nullable=False)
+ self._raise_on_invalid_uuid_literal(node)
if (
USE_GLOBAL_JOINS
@@ -2276,6 +2300,32 @@ class Resolver(CloningVisitor):
return node
+ def _raise_on_invalid_uuid_literal(self, node: ast.CompareOperation) -> None:
+ """A malformed string literal compared against a UUID column (events.uuid, person ids)
+ would fail the whole query at execution time with ClickHouse's CANNOT_PARSE_UUID —
+ reject it here instead, naming the bad value."""
+ if node.op not in _UUID_GUARDED_COMPARE_OPS:
+ return
+ for uuid_side, literal_side in ((node.left, node.right), (node.right, node.left)):
+ if not self._resolves_to_uuid(uuid_side):
+ continue
+ for constant in _string_constants(literal_side):
+ if not _UUID_LITERAL_RE.fullmatch(constant.value):
+ field_name = getattr(uuid_side.type, "name", None) or getattr(uuid_side.type, "alias", None)
+ subject = f"'{field_name}'" if isinstance(field_name, str) else "a UUID column"
+ raise QueryError(
+ f"'{constant.value}' is not a valid UUID, so it can never match {subject}. "
+ f"Use the full UUID, for example '0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b'."
+ )
+
+ def _resolves_to_uuid(self, node: ast.Expr) -> bool:
+ if node.type is None or isinstance(node, ast.Constant):
+ return False
+ try:
+ return isinstance(node.type.resolve_constant_type(self.context), ast.UUIDType)
+ except Exception:
+ return False
+
def _get_scope(self):
if len(self.scopes) > 0:
return self.scopes[-1]
diff --git a/posthog/hogql/test/__snapshots__/test_resolver.ambr b/posthog/hogql/test/__snapshots__/test_resolver.ambr
index f20cd9203551..542695b35a5c 100644
--- a/posthog/hogql/test/__snapshots__/test_resolver.ambr
+++ b/posthog/hogql/test/__snapshots__/test_resolver.ambr
@@ -907,17 +907,17 @@
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -3014,17 +3014,17 @@
arg_types: [
<recursion ...>,
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -5467,15 +5467,15 @@
nullable: False
},
event_issue_id: {
- data_type: "str"
+ data_type: "uuid"
nullable: True
},
event_person_id: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
issue_assigned_role_id: {
- data_type: "str"
+ data_type: "uuid"
nullable: True
},
issue_assigned_user_id: {
@@ -5507,7 +5507,7 @@
nullable: True
},
person_id: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
person_mode: {
@@ -5523,7 +5523,7 @@
nullable: False
},
uuid: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -6423,17 +6423,17 @@
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -7368,17 +7368,17 @@
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -10555,17 +10555,17 @@
arg_types: [
<recursion ...>,
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
@@ -12350,17 +12350,17 @@
arg_types: [
<recursion ...>,
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
},
{
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
]
name: "if"
return_type: {
- data_type: "str"
+ data_type: "uuid"
nullable: False
}
}
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.py
index 5a8af34d8d6e..a8a5b0131820 100644
--- a/posthog/hogql/test/test_metadata.py
+++ b/posthog/hogql/test/test_metadata.py
@@ -630,7 +630,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"query": query,
"notices": [
{
- "message": "Field 'person_id' is of type 'String'",
+ "message": "Field 'person_id' is of type 'UUID'",
"start": 7,
"end": 16,
"fix": None,
@@ -642,7 +642,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"fix": f"'{cohort.name}'",
},
{
- "message": "Field 'person_id' is of type 'String'",
+ "message": "Field 'person_id' is of type 'UUID'",
"start": 35,
"end": 44,
"fix": None,
@@ -654,7 +654,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"fix": str(cohort.pk),
},
{
- "message": "Field 'person_id' is of type 'String'",
+ "message": "Field 'person_id' is of type 'UUID'",
"start": 59 + len(str(cohort.pk)),
"end": 68 + len(str(cohort.pk)),
"fix": None,
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index 9d6b1cbbedc9..61f2c7109ed5 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -26,6 +26,7 @@ from posthog.hogql.database.models import (
StringJSONDatabaseField,
Table,
TableNode,
+ UUIDDatabaseField,
)
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.persons import PersonsTable
@@ -1255,7 +1256,7 @@ class TestResolver(BaseTest):
nullable=False,
description="Event name, e.g. '$pageview' or 'purchase'. Autocapture/PostHog events are prefixed with '$'.",
)
- assert cast(ast.FieldType, node.select[1].type).resolve_database_field(self.context) == StringDatabaseField(
+ assert cast(ast.FieldType, node.select[1].type).resolve_database_field(self.context) == UUIDDatabaseField(
name="person_id",
array=None,
nullable=False,
@@ -2081,3 +2082,38 @@ class TestResolver(BaseTest):
expr = self._select(query)
with self.assertRaisesRegex(QueryError, "Cannot access property.*renaming the alias"):
resolve_types(expr, self.context, dialect="clickhouse")
+
+ # A malformed string literal compared to a UUID column (events.uuid, person ids) would fail
+ # the whole query at ClickHouse execution time with the opaque CANNOT_PARSE_UUID, so the
+ # resolver must reject it with a message naming the value
+ @parameterized.expand(
+ [
+ ("person_id_eq", "SELECT event FROM events WHERE person_id = '2026072018044213140'"),
+ ("person_id_literal_on_left", "SELECT event FROM events WHERE '2026072018044213140' != person_id"),
+ (
+ "events_uuid_in_tuple",
+ "SELECT event FROM events WHERE uuid IN ('0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b', 'nope')",
+ ),
+ ("person_subtable_id", "SELECT event FROM events WHERE person.id = 'not-a-uuid'"),
+ (
+ "trailing_newline",
+ "SELECT event FROM events WHERE person_id = '0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b\n'",
+ ),
+ ("persons_scope_id", "SELECT id FROM persons WHERE id = 'not-a-uuid'"),
+ ]
+ )
+ def test_invalid_uuid_literal_comparison_raises(self, _name, query):
+ expr = self._select(query)
+ with self.assertRaisesRegex(QueryError, "is not a valid UUID"):
+ resolve_types(expr, self.context, dialect="clickhouse")
+
+ @parameterized.expand(
+ [
+ ("valid_uuid", "SELECT event FROM events WHERE person_id = '0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b'"),
+ ("string_column_untouched", "SELECT event FROM events WHERE distinct_id = 'not-a-uuid'"),
+ ("subquery_untouched", "SELECT event FROM events WHERE person_id IN (SELECT person_id FROM events)"),
+ ]
+ )
+ def test_uuid_literal_comparison_allows(self, _name, query):
+ expr = self._select(query)
+ resolve_types(expr, self.context, dialect="clickhouse")
diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.py
index b6ea16194d54..daa9e08f3bf8 100644
--- a/posthog/hogql/type_system.py
+++ b/posthog/hogql/type_system.py
@@ -693,8 +693,8 @@ def parse_clickhouse_type(type_name: str) -> RuntimeType:
# Scalar constant types whose runtime type is fully determined by (class, nullable) — used to
# dedupe before unification so large homogeneous literal arrays don't allocate per element.
-# Only families where unifying N identical types equals unifying one belong here; UUIDType and
-# IntervalType don't (a lone uuid keeps its family, but several unify to string via the subset rule).
+# Only families where unifying N identical types equals unifying one belong here; IntervalType
+# doesn't (a lone interval keeps its family, but several unify via the subset rules).
_SIMPLE_CONSTANT_TYPE_CLASSES = frozenset(
{
ast.BooleanType,
@@ -706,6 +706,7 @@ _SIMPLE_CONSTANT_TYPE_CLASSES = frozenset(
ast.StringArrayType,
ast.DateType,
ast.DateTimeType,
+ ast.UUIDType,
}
)
@@ -758,6 +759,8 @@ def least_common_runtime_type(runtime_types: list[RuntimeType], dialect: HogQLDi
if "datetime" in families
else DATE_RUNTIME_TYPE.with_nullable(nullable)
)
+ if families == {"uuid"}:
+ return RuntimeType(family="uuid", nullable=nullable, dialect=cast(RuntimeTypeDialect, dialect))
if families <= {"string", "fixed_string", "enum", "uuid"}:
return STRING_RUNTIME_TYPE.with_nullable(nullable)
if families == {"json"}: