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.

feat(hogql): resolve expression types and fix warehouse descriptions in information_schema (#66004)

Tom Owersfc7c6825d7de
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index 168c0a61645e..25cb298f77c8 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -45,6 +45,7 @@ from posthog.hogql.database.models import (
UUIDDatabaseField,
VirtualTable,
)
+from posthog.hogql.errors import BaseHogQLError
if TYPE_CHECKING:
from posthog.hogql.context import HogQLContext
@@ -134,6 +135,17 @@ _FIELD_TYPE_NAMES: list[tuple[type, str]] = [
]
+def _capture_unexpected(message: str, error: Exception) -> None:
+ """Surface a genuinely-unexpected resolution failure (a bug, not an unresolvable field) to error
+ tracking — expected `BaseHogQLError`s are handled by the caller and never sent here."""
+ # Deferred: keeps the (heavier) capture dependency off this schema module's import path.
+ from posthog.exceptions_capture import capture_exception # noqa: PLC0415
+
+ tracking_error = Exception(message)
+ tracking_error.__cause__ = error
+ capture_exception(tracking_error)
+
+
def _field_type_name(field: DatabaseField) -> str:
if isinstance(field, ExpressionField):
return "Expression"
@@ -168,7 +180,7 @@ def _warehouse_metadata(
"""Lazily load warehouse semantic descriptions and row counts for the team.
Returns `(descriptions, row_counts, view_row_counts)`. Descriptions are keyed by
- `(table_name, column_name)` with `""` denoting the table-level description. `row_counts` is keyed
+ `(table_id, column_name)` with `""` denoting the table-level description. `row_counts` is keyed
by warehouse table name, `view_row_counts` by saved-query (view) name. Only runs when an
information_schema table is actually queried, so it never touches the hot
`create_hogql_database` path. Mirrors how `serialize_database` sources counts so the catalog and
@@ -190,10 +202,14 @@ def _warehouse_metadata(
try:
with team_scope(team_id):
- for table_name, column_name, description in WarehouseColumnAnnotation.objects.values_list(
- "table__name", "column_name", "description"
+ # Key by table UUID, not name: the catalog entry's `table.name` is the source-prefixed
+ # key (e.g. `stripe.prod.charge`) while the annotation's `table__name` is the raw model
+ # name (e.g. `prod_stripe_charge`), so a name-keyed lookup never matches a synced table.
+ # `column_name=""` is the table-level description.
+ for table_id, column_name, description in WarehouseColumnAnnotation.objects.values_list(
+ "table_id", "column_name", "description"
):
- descriptions[(table_name, column_name)] = description
+ descriptions[(str(table_id), column_name)] = description
# `DataWarehouseTable` is on the IDOR baseline (not team-scoped), so `team_scope` is a
# no-op for it — filter by team_id explicitly or it reads every team's tables. `.queryable()`
# (not `.objects`) drops soft-deleted tables and orphans of a soft-deleted source —
@@ -399,10 +415,56 @@ class _Introspection:
self, database: "Database", context: "HogQLContext", allowed_tables: Optional[frozenset[str]] = None
) -> None:
self.database = database
+ self.context = context
self.allowed_tables = allowed_tables
self.warehouse = set(database.get_warehouse_table_names())
self.views = set(database.get_view_names())
self.descriptions, self.row_counts, self.view_row_counts = _warehouse_metadata(context.team_id)
+ # Resolved `SELECT * FROM <table>` scope per table, so expression columns can be typed without
+ # re-resolving the table once per expression.
+ self._table_scope_cache: dict[str, Optional[ast.SelectQueryType]] = {}
+
+ def _data_type(self, table_name: str, field: DatabaseField) -> str:
+ if isinstance(field, ExpressionField):
+ return self._expression_data_type(table_name, field)
+ return _field_type_name(field)
+
+ def _table_scope(self, table_name: str) -> Optional["ast.SelectQueryType"]:
+ if table_name not in self._table_scope_cache:
+ # Deferred: resolver imports the schema package, so a module-level import would cycle.
+ from posthog.hogql.resolver import resolve_table_scope # noqa: PLC0415
+
+ scope: Optional[ast.SelectQueryType] = None
+ try:
+ scope = resolve_table_scope(table_name.replace("`", "").split("."), self.context, "hogql")
+ except BaseHogQLError:
+ scope = None # genuinely unresolvable table — expected, fall back quietly
+ except Exception as e:
+ _capture_unexpected("information_schema: failed to resolve table scope", e)
+ self._table_scope_cache[table_name] = scope
+ return self._table_scope_cache[table_name]
+
+ def _expression_data_type(self, table_name: str, field: ExpressionField) -> str:
+ """Type an expression column by the value it evaluates to, like the HogQL autocomplete does;
+ fall back to the generic "Expression" if it can't be resolved."""
+ scope = self._table_scope(table_name)
+ if scope is None:
+ return "Expression"
+ # Deferred: see `_table_scope`.
+ from posthog.hogql.resolver import resolve_types # noqa: PLC0415
+ from posthog.hogql.visitor import clone_expr # noqa: PLC0415
+
+ try:
+ # Clone so resolution never mutates the shared schema field's expression.
+ resolved = resolve_types(clone_expr(field.expr, clear_locations=True), self.context, "hogql", [scope])
+ if resolved.type is None:
+ return "Expression"
+ return resolved.type.resolve_constant_type(self.context).print_type()
+ except BaseHogQLError:
+ return "Expression" # genuinely unresolvable expression — expected
+ except Exception as e:
+ _capture_unexpected("information_schema: failed to resolve expression column type", e)
+ return "Expression"
def _row_count(self, name: str, table: Table, table_type: str) -> Optional[int]:
if table_type == "data_warehouse" and table.name:
@@ -415,8 +477,9 @@ class _Introspection:
def _table_description(self, table: Table, table_type: str) -> Optional[str]:
if table.description:
return table.description
- if table_type == "data_warehouse" and table.name:
- return self.descriptions.get((table.name, ""))
+ table_id = getattr(table, "table_id", None)
+ if table_type == "data_warehouse" and table_id:
+ return self.descriptions.get((str(table_id), ""))
return None
def _column_description(
@@ -424,8 +487,9 @@ class _Introspection:
) -> Optional[str]:
if field.description:
return field.description
- if table_type == "data_warehouse" and table.name:
- return self.descriptions.get((table.name, column_name))
+ table_id = getattr(table, "table_id", None)
+ if table_type == "data_warehouse" and table_id:
+ return self.descriptions.get((str(table_id), column_name))
return None
def collect(self) -> tuple[list[list[Any]], list[list[Any]], list[list[Any]]]:
@@ -482,7 +546,7 @@ class _Introspection:
table_name,
qualified,
ordinal,
- _field_type_name(field),
+ self._data_type(table_name, field),
bool(field.is_nullable()),
bool(field.array),
kind,
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index 69ee6263049e..f138309d6a36 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -151,6 +151,30 @@ class TestWarehouseMetadata(APIBaseTest):
_descriptions, row_counts, _view_row_counts = _warehouse_metadata(self.team.id)
assert row_counts["shared"] == 7
+ def test_descriptions_are_keyed_by_table_id_not_name(self):
+ # A synced table's catalog name (source-prefixed) differs from its model name, so descriptions
+ # must key by table UUID — keying by name silently dropped every annotation in production.
+ table = self._table("orders", 100)
+ with team_scope(self.team.id, canonical=True):
+ WarehouseColumnAnnotation.objects.create(
+ team=self.team,
+ table=table,
+ column_name="",
+ description="All orders placed by customers.",
+ description_source=WarehouseColumnAnnotation.DescriptionSource.CANONICAL,
+ )
+ WarehouseColumnAnnotation.objects.create(
+ team=self.team,
+ table=table,
+ column_name="id",
+ description="Unique order identifier.",
+ description_source=WarehouseColumnAnnotation.DescriptionSource.USER_EDITED,
+ )
+ descriptions, _row_counts, _view_row_counts = _warehouse_metadata(self.team.id)
+ assert descriptions[(str(table.id), "")] == "All orders placed by customers."
+ assert descriptions[(str(table.id), "id")] == "Unique order identifier."
+ assert ("orders", "") not in descriptions
+
class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
def _context(self, db: Database) -> HogQLContext:
@@ -202,6 +226,27 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
assert "system.cohorts" in names
assert "system.feature_flags" not in names
+ @parameterized.expand(
+ [
+ ("person_id", "String"),
+ ("event_issue_id", "UUID"),
+ ("issue_first_seen", "DateTime"),
+ ("$virt_is_bot", "Boolean"),
+ ]
+ )
+ def test_expression_columns_resolve_to_their_value_type(self, column_name: str, expected_type: str):
+ # Expression columns must report the type they evaluate to (like hogql autocomplete), not the
+ # generic "Expression" — otherwise the catalog is useless for picking a cast/comparison.
+ response = execute_hogql_query(
+ f"SELECT data_type, field_kind FROM system.information_schema.columns "
+ f"WHERE table_name = 'events' AND column_name = '{column_name}'",
+ team=self.team,
+ )
+ results = response.results or []
+ assert len(results) == 1
+ assert results[0][1] == "expression"
+ assert results[0][0] == expected_type
+
def test_columns_lists_event_columns_with_types(self):
response = execute_hogql_query(
"""
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index fd5c7c8289f8..9c82feb5e5cb 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -144,9 +144,10 @@ def resolve_constant_data_type(constant: Any) -> ConstantType:
raise ImpossibleASTError(f"Unsupported constant type: {type(constant)}")
-def resolve_types_from_table(
- expr: ast.Expr, table_chain: list[str], context: HogQLContext, dialect: HogQLDialect
-) -> ast.Expr:
+def resolve_table_scope(table_chain: list[str], context: HogQLContext, dialect: HogQLDialect) -> ast.SelectQueryType:
+ """Resolve `SELECT * FROM <table_chain>` and return its query scope — the type other expressions
+ resolve against to reference the table's columns. Raises `QueryError` if the database/table is
+ unavailable. Caching, if wanted, is the caller's concern."""
if context.database is None:
raise QueryError("Database needs to be defined")
@@ -159,8 +160,14 @@ def resolve_types_from_table(
)
select_node_with_types = cast(ast.SelectQuery, resolve_types(select_node, context, dialect))
assert select_node_with_types.type is not None
+ return select_node_with_types.type
+
- return resolve_types(expr, context, dialect, [select_node_with_types.type])
+def resolve_types_from_table(
+ expr: ast.Expr, table_chain: list[str], context: HogQLContext, dialect: HogQLDialect
+) -> ast.Expr:
+ scope = resolve_table_scope(table_chain, context, dialect)
+ return resolve_types(expr, context, dialect, [scope])
ResolverFactory = Callable[