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(hogql): canonicalize UUID literals instead of rejecting them (#87648)

Thomas Obermüller64a168b617f2
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 58968ccdecbd..be41c24111b5 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -1,4 +1,4 @@
-import re
+import string
from collections.abc import Callable
from datetime import date, datetime
from typing import Any, Optional, cast
@@ -73,10 +73,6 @@ 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,
@@ -87,6 +83,19 @@ _UUID_GUARDED_COMPARE_OPS = (
)
+def _canonical_uuid(value: str) -> str | None:
+ """The canonical dashed-hex form ClickHouse can parse, or None if the value isn't a UUID at all.
+
+ Python's parser is deliberately more forgiving than ClickHouse's — surrounding whitespace,
+ braces, a `urn:uuid:` prefix and the undashed 32-hex form all describe the same UUID, so they
+ get normalized rather than rejected.
+ """
+ try:
+ return str(UUID(value.strip()))
+ except ValueError:
+ return None
+
+
def _string_constants(node: ast.Expr) -> list[ast.Constant]:
if isinstance(node, ast.Constant):
return [node] if isinstance(node.value, str) else []
@@ -2575,9 +2584,10 @@ class Resolver(CloningVisitor):
def _raise_on_invalid_uuid_literal(self, node: ast.CompareOperation) -> None:
"""A malformed string literal compared against a UUID column (events.uuid, person ids,
warehouse UUID columns) would fail the whole query at execution time with ClickHouse's
- CANNOT_PARSE_UUID — reject it here instead, naming the bad value. Only ClickHouse-bound
- queries are guarded: other target dialects (postgres, snowflake, ...) accept UUID text
- forms ClickHouse doesn't, so rejecting the canonical-form mismatch there would be wrong."""
+ CANNOT_PARSE_UUID. Rewrite the ones that are recognizably a UUID into the canonical form
+ ClickHouse accepts, and reject only what can't be a UUID at all. Only ClickHouse-bound
+ queries are touched: other target dialects (postgres, snowflake, ...) accept UUID text
+ forms ClickHouse doesn't, so normalizing or rejecting there would be wrong."""
if self.dialect not in ("clickhouse", "hogql"):
return
if node.op not in _UUID_GUARDED_COMPARE_OPS:
@@ -2586,13 +2596,26 @@ class Resolver(CloningVisitor):
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'."
- )
+ canonical = _canonical_uuid(constant.value)
+ if canonical is not None:
+ constant.value = canonical
+ continue
+ 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"
+ stripped = constant.value.strip()
+ # The digit count only helps a near miss like a truncated id; on text that was never
+ # a UUID attempt it reads as noise, so save it for the values it explains.
+ near_miss = bool(stripped) and all(char in string.hexdigits or char == "-" for char in stripped)
+ detail = (
+ f" A UUID has 32 hexadecimal digits and this one has "
+ f"{sum(1 for char in stripped if char in string.hexdigits)}."
+ if near_miss
+ else ""
+ )
+ raise QueryError(
+ f"{constant.value!r} can never match {subject}, which holds UUIDs.{detail} "
+ f"Enter a full UUID, like '0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b'."
+ )
def _resolves_to_uuid(self, node: ast.Expr) -> bool:
if node.type is None or isinstance(node, ast.Constant):
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index a3722e9c689c..00392c91197b 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -2095,17 +2095,52 @@ class TestResolver(BaseTest):
"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"):
+ with self.assertRaisesRegex(QueryError, "can never match .*, which holds UUIDs"):
+ resolve_types(expr, self.context, dialect="clickhouse")
+
+ def test_invalid_uuid_literal_message_makes_whitespace_visible(self):
+ # the value and the suggested example must not read as the same string on screen
+ expr = self._select("SELECT event FROM events WHERE person_id = 'not a uuid '")
+ with self.assertRaisesRegex(QueryError, r"'not a uuid '"):
+ resolve_types(expr, self.context, dialect="clickhouse")
+
+ @parameterized.expand(
+ [
+ # a truncated id is a near miss, so the digit count explains the mismatch
+ ("truncated_uuid", "'0198a4c2-8b3d'", True),
+ ("numeric_id", "'2026072018044213140'", True),
+ # on text that was never a UUID attempt the same count would just read as noise
+ ("arbitrary_text", "'not a uuid'", False),
+ ]
+ )
+ def test_invalid_uuid_literal_message_counts_digits_only_for_near_misses(self, _name, literal, expects_count):
+ expr = self._select(f"SELECT event FROM events WHERE person_id = {literal}")
+ with self.assertRaises(QueryError) as raised:
resolve_types(expr, self.context, dialect="clickhouse")
+ assert ("hexadecimal digits" in str(raised.exception)) is expects_count
+
+ # ClickHouse only parses the canonical dashed-hex form, but these all name the same UUID —
+ # normalize them instead of dead-ending a user who pasted one
+ @parameterized.expand(
+ [
+ ("trailing_newline", "'0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b\n'"),
+ ("surrounding_whitespace", "' 0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b '"),
+ ("uppercase", "'0198A4C2-8B3D-7E50-B4A1-2F9C6D8E0A1B'"),
+ ("no_dashes", "'0198a4c28b3d7e50b4a12f9c6d8e0a1b'"),
+ ("braces", "'{0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b}'"),
+ ("urn_prefix", "'urn:uuid:0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b'"),
+ ]
+ )
+ def test_non_canonical_uuid_literal_is_canonicalized(self, _name, literal):
+ expr = self._select(f"SELECT event FROM events WHERE person_id = {literal}")
+ resolved = cast(ast.SelectQuery, resolve_types(expr, self.context, dialect="clickhouse"))
+ where = cast(ast.CompareOperation, resolved.where)
+ assert cast(ast.Constant, where.right).value == "0198a4c2-8b3d-7e50-b4a1-2f9c6d8e0a1b"
@parameterized.expand(
[