: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
feat(hogql): resolve reference types for type coverage observability (#63210)
George Munyorofaf2cca541c9
diff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.pyindex 71b8151a642b..a50881a873df 100644--- a/posthog/hogql/observability.py+++ b/posthog/hogql/observability.py@@ -13,7 +13,7 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom random import randomfrom time import perf_counter-from typing import Literal, TypeVar, cast+from typing import TYPE_CHECKING, Literal, TypeVar, castimport structlogfrom prometheus_client import (@@ -26,6 +26,9 @@ from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.query_tagging import Product, get_query_tags+if TYPE_CHECKING:+ from posthog.hogql.context import HogQLContext+logger = structlog.get_logger(__name__)Precision = Literal["precise", "partial", "unknown"]@@ -275,18 +278,48 @@ def _source_from_query_tags() -> str:return str(getattr(product, "value", product))-def classify_expr_type(type_: ast.Type | None) -> Precision:+def classify_expr_type(type_: ast.Type | None, context: HogQLContext | None = None) -> Precision:if type_ is None or isinstance(type_, ast.UnknownType):return "unknown"if isinstance(type_, ast.CallType):return classify_constant_type(type_.return_type)if isinstance(type_, ast.FieldAliasType):- return classify_expr_type(type_.type)+ return classify_expr_type(type_.type, context)if isinstance(type_, ast.ConstantType):return classify_constant_type(type_)+ # FieldType/PropertyType hide a concrete scalar behind a reference; resolve it if we have a+ # context. Other catch-all types (SelectQueryType, LazyJoinType, AsteriskType, lambda types)+ # genuinely lack a scalar, so they skip resolution and stay "partial".+ if context is not None and isinstance(type_, (ast.FieldType, ast.PropertyType)):+ return _classify_via_resolution(type_, context)return "partial"+def _classify_via_resolution(type_: ast.FieldType | ast.PropertyType, context: HogQLContext) -> Precision:+ """Classify by the resolved scalar. For properties, follow PropertyType.resolve_constant_type's+ precedence but stop before its nullable-String fallback: no metadata means "partial", not+ precise-via-String."""+ from posthog.hogql.property_planner import (+ metadata_constant_type, # noqa: PLC0415 — observability ← context ← property_planner; deferring breaks the cycle+ )++ try:+ if isinstance(type_, ast.FieldType):+ return classify_constant_type(type_.resolve_constant_type(context))+ if (type_.joined_subquery is not None and type_.joined_subquery_field_name is not None) or isinstance(+ type_.field_type.resolve_database_field(context), ast.StructDatabaseField+ ):+ return classify_constant_type(type_.resolve_constant_type(context))+ metadata_type = metadata_constant_type(type_, context)+ if metadata_type is None:+ return "partial"+ return classify_constant_type(metadata_type)+ except Exception:+ # Resolution can raise for genuinely unresolvable references — expected, so "partial"+ # without bumping the observability error counter.+ return "partial"++def classify_constant_type(type_: ast.ConstantType | None) -> Precision:if type_ is None or isinstance(type_, ast.UnknownType):return "unknown"@@ -337,10 +370,12 @@ def classify_function_group(function_name: str) -> str:@_safe-def collect_hogql_type_coverage(node: ast.AST, stats: HogQLTypeObservability | None) -> None:+def collect_hogql_type_coverage(+ node: ast.AST, stats: HogQLTypeObservability | None, context: HogQLContext | None = None+) -> None:if stats is None:return- TypeCoverageCollector(stats).visit(node)+ TypeCoverageCollector(stats, context).visit(node)@_safe@@ -376,14 +411,15 @@ def emit_hogql_type_observability(stats: HogQLTypeObservability | None) -> None:class TypeCoverageCollector(TraversingVisitor):- def __init__(self, stats: HogQLTypeObservability):+ def __init__(self, stats: HogQLTypeObservability, context: HogQLContext | None = None):super().__init__()self.stats = stats+ self.context = contextdef visit(self, node: ast.AST | None) -> None:if isinstance(node, ast.Expr):self.stats.expression_count += 1- self.stats.typed_by_precision[classify_expr_type(node.type)] += 1+ self.stats.typed_by_precision[classify_expr_type(node.type, self.context)] += 1return super().visit(node)diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 49246100aabf..a81dbb0494f9 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -77,7 +77,7 @@ def prepare_and_print_ast(context.type_observability.result = "empty"return "", None- collect_hogql_type_coverage(prepared_ast, context.type_observability)+ collect_hogql_type_coverage(prepared_ast, context.type_observability, context)collect_hogql_sql_shape(prepared_ast, context.type_observability)printed = print_prepared_ast(diff --git a/posthog/hogql/test/test_observability.py b/posthog/hogql/test/test_observability.pyindex 12146db38ceb..b8cb43e836c0 100644--- a/posthog/hogql/test/test_observability.py+++ b/posthog/hogql/test/test_observability.py@@ -1,3 +1,4 @@+from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.test import SimpleTestCase@@ -6,6 +7,8 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.observability import (HogQLTypeObservability,classify_constant_type,@@ -16,8 +19,14 @@ from posthog.hogql.observability import (create_hogql_type_observability,emit_hogql_type_observability,)+from posthog.hogql.parser import parse_select+from posthog.hogql.resolver import resolve_types+from posthog.hogql.transforms.property_types import build_property_swapperfrom posthog.clickhouse.query_tagging import Product+from posthog.models import PropertyDefinition++from products.event_definitions.backend.models.property_definition import PropertyType as PropertyDefinitionTypedef _metric(name: str, labels: dict[str, str]) -> float:@@ -192,3 +201,78 @@ class TestHogQLTypeObservability(SimpleTestCase):)def test_function_groups_are_bounded(self, name, expected):self.assertEqual(classify_function_group(name), expected)+++class TestTypeCoverageResolution(BaseTest):+ """Reference types (columns, properties) only resolve to a concrete scalar against a context."""++ def setUp(self):+ super().setUp()+ self.database = Database.create_for(team=self.team)+ self.context = HogQLContext(database=self.database, team_id=self.team.pk, enable_select_queries=True)++ def _resolved_column_type(self, query: str) -> ast.Type | None:+ node = parse_select(query)+ node = resolve_types(node, self.context, dialect="clickhouse")+ assert isinstance(node, ast.SelectQuery)+ # Populates context.property_swapper, which the property metadata path reads from.+ build_property_swapper(node, self.context)+ column_type = node.select[0].type+ # Selected columns are wrapped in a FieldAliasType; unwrap to the underlying reference.+ if isinstance(column_type, ast.FieldAliasType):+ return column_type.type+ return column_type++ def test_bare_field_with_typed_column_is_precise(self):+ field_type = self._resolved_column_type("SELECT timestamp FROM events")+ self.assertIsInstance(field_type, ast.FieldType)++ self.assertEqual(classify_expr_type(field_type, self.context), "precise")+ # No context → cannot resolve → partial.+ self.assertEqual(classify_expr_type(field_type), "partial")++ def test_property_with_metadata_is_precise(self):+ PropertyDefinition.objects.create(+ team=self.team,+ name="foo",+ property_type=PropertyDefinitionType.Numeric,+ type=PropertyDefinition.Type.EVENT,+ )+ property_type = self._resolved_column_type("SELECT properties.foo FROM events")+ self.assertIsInstance(property_type, ast.PropertyType)++ self.assertEqual(classify_expr_type(property_type, self.context), "precise")++ def test_property_without_metadata_is_partial_not_string_fallback(self):+ property_type = self._resolved_column_type("SELECT properties.unknown_prop FROM events")+ assert isinstance(property_type, ast.PropertyType)++ # Resolution falls back to the blob's String type (classify_constant_type would call that+ # precise); the special-casing returns partial instead, since metadata is missing.+ self.assertEqual(classify_constant_type(property_type.resolve_constant_type(self.context)), "precise")+ self.assertEqual(classify_expr_type(property_type, self.context), "partial")++ def test_unresolvable_field_classifies_partial_without_raising(self):+ before_errors = _metric("hogql_type_observability_errors_total", {"stage": "collect_hogql_type_coverage"})++ # events.person is a lazy join, not a DatabaseField — resolve_constant_type raises.+ field_type = ast.FieldType(name="person", table_type=ast.TableType(table=self.database.get_table("events")))++ self.assertEqual(classify_expr_type(field_type, self.context), "partial")+ # An expected unresolvable reference must not inflate the error counter.+ self.assertEqual(+ _metric("hogql_type_observability_errors_total", {"stage": "collect_hogql_type_coverage"}), before_errors+ )++ @parameterized.expand(+ [+ ("array_of_string", ast.ArrayType(item_type=ast.StringType()), "precise"),+ ("array_of_unknown", ast.ArrayType(item_type=ast.UnknownType()), "unknown"),+ ("tuple_all_known", ast.TupleType(item_types=[ast.StringType(), ast.IntegerType()]), "precise"),+ ("tuple_with_unknown", ast.TupleType(item_types=[ast.StringType(), ast.UnknownType()]), "unknown"),+ ]+ )+ def test_constant_types_recurse_unchanged_with_context(self, _name, type_, expected):+ # A threaded context must not change how constant types already classify.+ self.assertEqual(classify_expr_type(type_, self.context), expected)+ self.assertEqual(classify_expr_type(type_), expected)