: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): add type-system observability instrumentation (#61248)
George Munyorod6e58622f78b
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex 29fc51e4329a..deda14509bd3 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -11,6 +11,7 @@ from posthog.clickhouse.workload import Workloadif TYPE_CHECKING:from posthog.hogql.database.database import Database+ from posthog.hogql.observability import HogQLTypeObservabilityfrom posthog.hogql.transforms.property_types import PropertySwapperfrom posthog.models import Team, User@@ -76,6 +77,11 @@ class HogQLContext:# Enables more verbose output for debuggingdebug: bool = False+ # Optional per-query HogQL type-system observability accumulator.+ type_observability: Optional["HogQLTypeObservability"] = None+ # Bounded source/surface label for type-system observability metrics.+ observability_source: str = "unknown"+property_swapper: Optional["PropertySwapper"] = None# Workload detected during AST resolution (set by prepare_ast_for_printing)workload: Optional[Workload] = Nonediff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.pynew file mode 100644index 000000000000..4de3224b5419--- /dev/null+++ b/posthog/hogql/observability.py@@ -0,0 +1,406 @@+"""HogQL type-system observability.++Measures type-inference coverage and the shape of the generated SQL during each+prepare+typecheck pass, emitted as low-cardinality Prometheus metrics. Sampling is+gated by ``TYPE_OBSERVABILITY_SAMPLE_RATE``.+"""++from __future__ import annotations++import functools+from collections import Counter+from collections.abc import Callable+from dataclasses import dataclass, field+from random import random+from time import perf_counter+from typing import Literal, TypeVar, cast++import structlog+from prometheus_client import (+ Counter as PromCounter,+ Histogram,+)++from posthog.hogql import ast+from posthog.hogql.visitor import TraversingVisitor++logger = structlog.get_logger(__name__)++Precision = Literal["precise", "partial", "unknown"]+Labels = dict[str, str]+_F = TypeVar("_F", bound=Callable[..., object])++_BASE_LABELS = ["engine", "dialect", "source"]++TYPECHECK_TOTAL = PromCounter(+ "hogql_typecheck_total",+ "HogQL prepare+typecheck passes by result.",+ labelnames=[*_BASE_LABELS, "result"],+)+TYPECHECK_DURATION_SECONDS = Histogram(+ "hogql_typecheck_duration_seconds",+ "Wall-clock duration of a HogQL prepare+typecheck pass.",+ labelnames=_BASE_LABELS,+ buckets=(0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),+)+EXPRESSION_OBSERVED_TOTAL = PromCounter(+ "hogql_expression_observed_total",+ "HogQL AST expressions visited during type-coverage sampling.",+ labelnames=_BASE_LABELS,+)+EXPRESSION_TYPED_TOTAL = PromCounter(+ "hogql_expression_typed_total",+ "HogQL expressions by inferred type precision.",+ labelnames=[*_BASE_LABELS, "precision"],+)+TYPE_UNKNOWN_TOTAL = PromCounter(+ "hogql_type_unknown_total",+ "HogQL type-inference gaps by reason.",+ labelnames=[*_BASE_LABELS, "reason"],+)+FUNCTION_CALL_TOTAL = PromCounter(+ "hogql_function_call_total",+ "HogQL function calls observed during resolution.",+ labelnames=_BASE_LABELS,+)+FUNCTION_RETURN_TYPED_TOTAL = PromCounter(+ "hogql_function_return_typed_total",+ "HogQL function-call return types by precision.",+ labelnames=[*_BASE_LABELS, "precision"],+)+FUNCTION_SIGNATURE_MISS_TOTAL = PromCounter(+ "hogql_function_signature_miss_total",+ "Function calls with no signature metadata, by function group.",+ labelnames=[*_BASE_LABELS, "function_group"],+)+FUNCTION_SIGNATURE_MISMATCH_TOTAL = PromCounter(+ "hogql_function_signature_mismatch_total",+ "Function calls whose signatures did not resolve a return type, by function group.",+ labelnames=[*_BASE_LABELS, "function_group"],+)+PROPERTY_TYPING_TOTAL = PromCounter(+ "hogql_property_typing_total",+ "Property-definition lookups by source and known/unknown result.",+ labelnames=[*_BASE_LABELS, "result"],+)+MATERIALIZED_PROPERTY_USAGE_TOTAL = PromCounter(+ "hogql_materialized_property_usage_total",+ "Materialized vs JSON property access by result.",+ labelnames=[*_BASE_LABELS, "result"],+)+SQL_SHAPE_TOTAL = PromCounter(+ "hogql_sql_shape_total",+ "Generated SQL shape pathologies by kind.",+ labelnames=[*_BASE_LABELS, "shape"],+)+OBSERVABILITY_ERRORS_TOTAL = PromCounter(+ "hogql_type_observability_errors_total",+ "Swallowed exceptions raised inside the type-observability code itself, by stage. "+ "Observability never propagates its own failures into query execution; this counter makes them visible.",+ labelnames=["stage"],+)+++def _log_observability_error(stage: str) -> None:+ """Record and log a swallowed observability failure. Must never raise."""+ try:+ OBSERVABILITY_ERRORS_TOTAL.labels(stage=stage).inc()+ logger.warning("hogql_type_observability_error", stage=stage, exc_info=True)+ except Exception:+ pass+++def _safe(fn: _F) -> _F:+ """Wrap an observability entry point so its own exceptions can never reach the query path.++ Instrumentation must never break the thing it observes: on failure we log, count, and+ continue. Functions that produce a value return ``None`` when they fail.+ """++ @functools.wraps(fn)+ def wrapper(*args: object, **kwargs: object) -> object:+ try:+ return fn(*args, **kwargs)+ except Exception:+ _log_observability_error(fn.__name__)+ return None++ return cast(_F, wrapper)+++_UNKNOWN_REASONS = {+ "missing_function_signature",+ "signature_mismatch",+ "unsupported_ast_node",+ "unknown_property_metadata",+ "property_metadata_conflict",+ "unknown_database_field_type",+ "set_query_type_conflict",+ "lambda_type_unbound",+ "dialect_gap",+ "transform_invalidated_type",+ "inference_exception",+}++# Allowed values for the `source` label. Bounded to keep Prometheus label cardinality+# fixed even if a call site sets `context.observability_source` to a high-cardinality+# value (URL path, view name, …); anything off-list collapses to "unknown".+# Add new surfaces here as call sites are wired up.+_KNOWN_SOURCES = {+ "sql_editor",+ "insights",+ "api",+ "mcp",+ "subscription",+ "probe",+ "unknown",+}+++@dataclass+class HogQLTypeObservability:+ engine: str = "current"+ dialect: str = "unknown"+ source: str = "unknown"++ started_at: float = field(default_factory=perf_counter)+ result: str = "success"++ expression_count: int = 0+ typed_by_precision: Counter[str] = field(default_factory=Counter)+ unknown_by_reason: Counter[str] = field(default_factory=Counter)++ function_call_count: int = 0+ function_return_by_precision: Counter[str] = field(default_factory=Counter)+ function_signature_miss_by_group: Counter[str] = field(default_factory=Counter)+ function_signature_mismatch_by_group: Counter[str] = field(default_factory=Counter)++ property_typing: Counter[str] = field(default_factory=Counter)+ materialized_property_usage: Counter[str] = field(default_factory=Counter)++ sql_shape: Counter[str] = field(default_factory=Counter)++ def tags(self) -> Labels:+ return {+ "engine": self.engine,+ "dialect": self.dialect,+ "source": self.source,+ }++ @_safe+ def record_unknown(self, reason: str, count: int = 1) -> None:+ self.unknown_by_reason[_bounded(reason, _UNKNOWN_REASONS)] += count++ @_safe+ def record_function_call(self, function_name: str, return_type: ast.ConstantType, signatures_present: bool) -> None:+ self.function_call_count += 1+ precision = classify_constant_type(return_type)+ self.function_return_by_precision[precision] += 1++ if isinstance(return_type, ast.UnknownType):+ function_group = classify_function_group(function_name)+ if signatures_present:+ self.function_signature_mismatch_by_group[function_group] += 1+ self.record_unknown("signature_mismatch")+ else:+ self.function_signature_miss_by_group[function_group] += 1+ self.record_unknown("missing_function_signature")++ @_safe+ def record_property_definition_lookup(self, property_source: str, known_count: int, total_count: int) -> None:+ property_source = _bounded(property_source, {"event", "person", "group"})+ unknown_count = max(total_count - known_count, 0)+ self.property_typing[f"{property_source}_known"] += known_count+ self.property_typing[f"{property_source}_unknown"] += unknown_count+ if unknown_count:+ self.record_unknown("unknown_property_metadata", unknown_count)+++# Fraction of HogQL prepare+typecheck passes to instrument. The collectors walk the whole+# prepared AST, so sampling bounds that cost; set to 0 to disable instrumentation entirely.+TYPE_OBSERVABILITY_SAMPLE_RATE = 0.01+++@_safe+def create_hogql_type_observability(+ dialect: str, source: str = "unknown", engine: str = "current"+) -> HogQLTypeObservability | None:+ # Return an accumulator only when this pass is actually sampled. On the unsampled+ # majority we return None, so every per-pass hook (record_*/collect_*/emit_*)+ # short-circuits on a single `is not None` check — unsampled queries pay nothing+ # beyond the sampling draw below.+ if TYPE_OBSERVABILITY_SAMPLE_RATE <= 0 or random() >= TYPE_OBSERVABILITY_SAMPLE_RATE:+ return None+ return HogQLTypeObservability(+ engine=_clean_tag(engine),+ dialect=_clean_tag(dialect),+ source=_bounded(_clean_tag(source), _KNOWN_SOURCES),+ )+++def classify_expr_type(type_: ast.Type | 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)+ if isinstance(type_, ast.ConstantType):+ return classify_constant_type(type_)+ return "partial"+++def classify_constant_type(type_: ast.ConstantType | None) -> Precision:+ if type_ is None or isinstance(type_, ast.UnknownType):+ return "unknown"+ if isinstance(type_, ast.ArrayType):+ return classify_constant_type(type_.item_type)+ if isinstance(type_, ast.TupleType):+ item_precisions = {classify_constant_type(item_type) for item_type in type_.item_types}+ if "unknown" in item_precisions:+ return "unknown"+ if "partial" in item_precisions:+ return "partial"+ return "precise"+ return "precise"+++def classify_function_group(function_name: str) -> str:+ name = function_name.lower()++ if name in {"equals", "notequals", "less", "greater", "lessorequals", "greaterorequals", "in", "notin"}:+ return "comparison"+ if name in {"and", "or", "xor", "not", "if", "multiif"}:+ return "logical"+ if name.startswith("json") or "json" in name:+ return "json"+ if name.startswith("array"):+ return "array"+ if name.startswith("tuple"):+ return "tuple"+ if name.startswith("map"):+ return "map"+ if name.startswith("to") or "cast" in name:+ return "cast"+ if name in {"count", "sum", "avg", "min", "max", "uniq", "quantile"}:+ return "aggregate"+ if name.endswith("state") or name.endswith("merge"):+ return "aggregate_state"+ if "date" in name or "time" in name or name in {"now", "today", "yesterday"}:+ return "datetime"+ if name in {"concat", "substring", "lower", "upper", "replace", "match", "like", "ilike", "regexp"}:+ return "string"+ if "url" in name:+ return "url"+ if name in {"abs", "round", "floor", "ceil", "sqrt", "pow", "exp", "log"}:+ return "math"+ if name.startswith("hogql") or name.startswith("__"):+ return "posthog"+ return "unknown"+++@_safe+def collect_hogql_type_coverage(node: ast.AST, stats: HogQLTypeObservability | None) -> None:+ if stats is None:+ return+ TypeCoverageCollector(stats).visit(node)+++@_safe+def collect_hogql_sql_shape(node: ast.AST, stats: HogQLTypeObservability | None) -> None:+ if stats is None:+ return+ SQLShapeCollector(stats).visit(node)+++@_safe+def emit_hogql_type_observability(stats: HogQLTypeObservability | None) -> None:+ if stats is None:+ return++ base = stats.tags()+ TYPECHECK_TOTAL.labels(**base, result=_clean_tag(stats.result)).inc()+ TYPECHECK_DURATION_SECONDS.labels(**base).observe(max(0.0, perf_counter() - stats.started_at))++ if stats.expression_count:+ EXPRESSION_OBSERVED_TOTAL.labels(**base).inc(stats.expression_count)+ _emit_counter(EXPRESSION_TYPED_TOTAL, "precision", stats.typed_by_precision, base)+ _emit_counter(TYPE_UNKNOWN_TOTAL, "reason", stats.unknown_by_reason, base)++ if stats.function_call_count:+ FUNCTION_CALL_TOTAL.labels(**base).inc(stats.function_call_count)+ _emit_counter(FUNCTION_RETURN_TYPED_TOTAL, "precision", stats.function_return_by_precision, base)+ _emit_counter(FUNCTION_SIGNATURE_MISS_TOTAL, "function_group", stats.function_signature_miss_by_group, base)+ _emit_counter(FUNCTION_SIGNATURE_MISMATCH_TOTAL, "function_group", stats.function_signature_mismatch_by_group, base)+ _emit_counter(PROPERTY_TYPING_TOTAL, "result", stats.property_typing, base)+ _emit_counter(MATERIALIZED_PROPERTY_USAGE_TOTAL, "result", stats.materialized_property_usage, base)+ _emit_counter(SQL_SHAPE_TOTAL, "shape", stats.sql_shape, base)+++class TypeCoverageCollector(TraversingVisitor):+ def __init__(self, stats: HogQLTypeObservability):+ super().__init__()+ self.stats = stats++ def 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+ return super().visit(node)+++# Type-coercion cast functions. Every matching call is counted (regardless of whether its+# argument is a property, field, or constant) and each also bumps property_conversion_wrapper.+_CAST_SHAPES = {+ "todatetime": "datetime_cast",+ "todatetime64": "datetime_cast",+ "todate": "datetime_cast",+ "tofloat": "numeric_cast",+ "tofloat32": "numeric_cast",+ "tofloat64": "numeric_cast",+ "toint": "numeric_cast",+ "toint32": "numeric_cast",+ "toint64": "numeric_cast",+ "todecimal": "numeric_cast",+ "tostring": "string_cast",+ "tofixedstring": "string_cast",+ "tobool": "boolean_cast",+}+++class SQLShapeCollector(TraversingVisitor):+ def __init__(self, stats: HogQLTypeObservability):+ super().__init__()+ self.stats = stats++ def visit_call(self, node: ast.Call) -> None:+ name = node.name.lower()+ cast_shape = _CAST_SHAPES.get(name)+ if cast_shape is not None:+ self.stats.sql_shape[cast_shape] += 1+ self.stats.sql_shape["property_conversion_wrapper"] += 1+ elif name == "ifnull":+ self.stats.sql_shape["nullable_comparison_wrapper"] += 1+ elif name == "assumenotnull":+ self.stats.sql_shape["assume_not_null"] += 1+ elif name == "jsonextractraw":+ self.stats.sql_shape["json_extract_raw"] += 1+ elif name.startswith("jsonextract") or name in {"json_value", "jsonhas", "jsontype", "jsonlength"}:+ self.stats.sql_shape["json_extract"] += 1++ super().visit_call(node)+++def _emit_counter(metric: PromCounter, label_name: str, values: Counter[str], base: Labels) -> None:+ for label_value, count in values.items():+ if count:+ metric.labels(**base, **{label_name: _clean_tag(label_value)}).inc(count)+++def _bounded(value: str, allowed_values: set[str]) -> str:+ return value if value in allowed_values else "unknown"+++def _clean_tag(value: str) -> str:+ safe = "".join(character if character.isalnum() or character in {"_", "-"} else "_" for character in str(value))+ return safe[:64] or "unknown"diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex df057950595a..376d46cb483f 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -9,6 +9,12 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.errors import InternalHogQLErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_team, set_default_in_cohort_via+from posthog.hogql.observability import (+ collect_hogql_sql_shape,+ collect_hogql_type_coverage,+ create_hogql_type_observability,+ emit_hogql_type_observability,+)from posthog.hogql.printer.base import BasePrinterfrom posthog.hogql.printer.clickhouse import ClickHousePrinterfrom posthog.hogql.printer.duckdb import DuckDBPrinter@@ -50,20 +56,42 @@ def prepare_and_print_ast(settings: HogQLGlobalSettings | None = None,pretty: bool = False,) -> tuple[str, _T_AST | None]:- prepared_ast = prepare_ast_for_printing(node=node, context=context, dialect=dialect, stack=stack, settings=settings)- if prepared_ast is None:- return "", None- return (- print_prepared_ast(- node=prepared_ast,- context=context,- dialect=dialect,- stack=stack,- settings=settings,- pretty=pretty,- ),- prepared_ast,+ previous_type_observability = context.type_observability+ context.type_observability = create_hogql_type_observability(+ dialect=dialect,+ source=context.observability_source,)+ try:+ prepared_ast = prepare_ast_for_printing(+ node=node, context=context, dialect=dialect, stack=stack, settings=settings+ )+ if prepared_ast is None:+ if context.type_observability is not None:+ context.type_observability.result = "empty"+ return "", None++ collect_hogql_type_coverage(prepared_ast, context.type_observability)+ collect_hogql_sql_shape(prepared_ast, context.type_observability)++ return (+ print_prepared_ast(+ node=prepared_ast,+ context=context,+ dialect=dialect,+ stack=stack,+ settings=settings,+ pretty=pretty,+ ),+ prepared_ast,+ )+ except Exception:+ if context.type_observability is not None:+ context.type_observability.result = "error"+ context.type_observability.record_unknown("inference_exception")+ raise+ finally:+ emit_hogql_type_observability(context.type_observability)+ context.type_observability = previous_type_observabilitydef prepare_ast_for_printing(diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex a86546230030..1825c0a7ad90 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -1540,6 +1540,13 @@ class Resolver(CloningVisitor):elif node.name.lower() == "assumenotnull":return_type.nullable = False+ if self.context.type_observability is not None:+ self.context.type_observability.record_function_call(+ function_name=node.name,+ return_type=return_type,+ signatures_present=bool(func_meta and func_meta.signatures),+ )+node.type = ast.CallType(name=node.name,arg_types=arg_types,diff --git a/posthog/hogql/test/test_observability.py b/posthog/hogql/test/test_observability.pynew file mode 100644index 000000000000..16e6a06b4b59--- /dev/null+++ b/posthog/hogql/test/test_observability.py@@ -0,0 +1,143 @@+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from prometheus_client import REGISTRY++from posthog.hogql import ast+from posthog.hogql.observability import (+ HogQLTypeObservability,+ classify_constant_type,+ classify_expr_type,+ classify_function_group,+ collect_hogql_sql_shape,+ collect_hogql_type_coverage,+ create_hogql_type_observability,+ emit_hogql_type_observability,+)+++def _metric(name: str, labels: dict[str, str]) -> float:+ return REGISTRY.get_sample_value(name, labels) or 0.0+++class TestHogQLTypeObservability(SimpleTestCase):+ @patch("posthog.hogql.observability.TYPE_OBSERVABILITY_SAMPLE_RATE", 0.0)+ def test_zero_sample_rate_creates_no_accumulator(self):+ base = {"engine": "current", "dialect": "clickhouse", "source": "sql_editor"}+ before = _metric("hogql_typecheck_total", {**base, "result": "success"})++ stats = create_hogql_type_observability(dialect="clickhouse", source="sql_editor")++ self.assertIsNone(stats)+ emit_hogql_type_observability(stats) # no-op on None+ self.assertEqual(_metric("hogql_typecheck_total", {**base, "result": "success"}), before)++ @patch("posthog.hogql.observability.TYPE_OBSERVABILITY_SAMPLE_RATE", 1.0)+ def test_sampling_returns_accumulator(self):+ stats = create_hogql_type_observability(dialect="clickhouse", source="sql_editor")+ self.assertIsNotNone(stats)++ def test_observability_failures_never_propagate(self):+ # A bug anywhere in the observability path must not break query execution.+ stats = HogQLTypeObservability(dialect="clickhouse", source="sql_editor")+ before_errors = _metric("hogql_type_observability_errors_total", {"stage": "collect_hogql_type_coverage"})++ with patch("posthog.hogql.observability.TypeCoverageCollector", side_effect=RuntimeError("boom")):+ # Does not raise, despite the collector blowing up.+ collect_hogql_type_coverage(ast.Constant(value=1), stats)++ self.assertEqual(+ _metric("hogql_type_observability_errors_total", {"stage": "collect_hogql_type_coverage"}) - before_errors,+ 1,+ )++ def test_record_methods_swallow_bad_input(self):+ stats = HogQLTypeObservability(dialect="clickhouse", source="sql_editor")+ before_errors = _metric("hogql_type_observability_errors_total", {"stage": "record_function_call"})++ # function_name=None makes classify_function_group raise (None.lower()); @_safe must swallow it.+ stats.record_function_call(function_name=None, return_type=ast.UnknownType(), signatures_present=False) # type: ignore[arg-type]++ self.assertEqual(+ _metric("hogql_type_observability_errors_total", {"stage": "record_function_call"}) - before_errors, 1+ )+ emit_hogql_type_observability(stats) # must not raise++ @patch("posthog.hogql.observability.TYPE_OBSERVABILITY_SAMPLE_RATE", 1.0)+ def test_emits_expression_coverage_metrics_with_bounded_labels(self):+ base = {"engine": "current", "dialect": "clickhouse", "source": "sql_editor"}+ before_observed = _metric("hogql_expression_observed_total", base)+ before_precise = _metric("hogql_expression_typed_total", {**base, "precision": "precise"})+ before_unknown = _metric("hogql_expression_typed_total", {**base, "precision": "unknown"})++ stats = create_hogql_type_observability(dialect="clickhouse", source="sql_editor")+ node = ast.Array(+ exprs=[+ ast.Constant(value="known", type=ast.StringType()),+ ast.Call(name="unknownFunc", args=[], type=ast.UnknownType()),+ ],+ type=ast.ArrayType(item_type=ast.UnknownType()),+ )++ collect_hogql_type_coverage(node, stats)+ emit_hogql_type_observability(stats)++ self.assertEqual(_metric("hogql_expression_observed_total", base) - before_observed, 3)+ self.assertEqual(_metric("hogql_expression_typed_total", {**base, "precision": "precise"}) - before_precise, 1)+ self.assertEqual(_metric("hogql_expression_typed_total", {**base, "precision": "unknown"}) - before_unknown, 2)++ @parameterized.expand(+ [+ ("scalar", ast.StringType(), "precise"),+ ("unknown", ast.UnknownType(), "unknown"),+ ("array_of_unknown", ast.ArrayType(item_type=ast.UnknownType()), "unknown"),+ ]+ )+ def test_classifies_constant_type_precision(self, _name, type_, expected):+ self.assertEqual(classify_constant_type(type_), expected)++ def test_classifies_call_expr_precision(self):+ self.assertEqual(+ classify_expr_type(ast.CallType(name="concat", arg_types=[ast.StringType()], return_type=ast.StringType())),+ "precise",+ )++ def test_collects_sql_shape_pathologies_from_ast(self):+ stats = HogQLTypeObservability(dialect="clickhouse", source="sql_editor")+ node = ast.Call(+ name="ifNull",+ args=[+ ast.Call(name="toDateTime", args=[ast.Field(chain=["timestamp"])]),+ ast.Constant(value="fallback"),+ ],+ )++ collect_hogql_sql_shape(node, stats)++ self.assertEqual(stats.sql_shape["nullable_comparison_wrapper"], 1)+ self.assertEqual(stats.sql_shape["datetime_cast"], 1)+ self.assertEqual(stats.sql_shape["property_conversion_wrapper"], 1)++ def test_records_property_typing_results(self):+ stats = HogQLTypeObservability(dialect="clickhouse", source="sql_editor")++ stats.record_property_definition_lookup(property_source="event", known_count=2, total_count=3)+ stats.record_property_definition_lookup(property_source="person", known_count=1, total_count=1)++ self.assertEqual(stats.property_typing["event_known"], 2)+ self.assertEqual(stats.property_typing["event_unknown"], 1)+ self.assertEqual(stats.property_typing["person_known"], 1)+ self.assertEqual(stats.unknown_by_reason["unknown_property_metadata"], 1)++ @parameterized.expand(+ [+ ("toDateTime", "cast"),+ ("JSONExtractString", "json"),+ ("arrayMap", "array"),+ ("someCustomThing", "unknown"),+ ]+ )+ def test_function_groups_are_bounded(self, name, expected):+ self.assertEqual(classify_function_group(name), expected)diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex 3d8d2bc836e2..df1644489cee 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -123,6 +123,23 @@ def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:})+ if context.type_observability is not None:+ context.type_observability.record_property_definition_lookup(+ property_source="event",+ known_count=len(event_properties),+ total_count=len(property_finder.event_properties),+ )+ context.type_observability.record_property_definition_lookup(+ property_source="person",+ known_count=len(person_properties),+ total_count=len(property_finder.person_properties),+ )+ context.type_observability.record_property_definition_lookup(+ property_source="group",+ known_count=len(group_properties),+ total_count=sum(len(properties) for properties in property_finder.group_properties.values()),+ )+timezone = context.database.get_timezone() if context and context.database else "UTC"context.property_swapper = PropertySwapper(timezone=timezone,