: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(data-warehouse): surface column statistics in information_schema.columns (#66967)
Tom Owers779b400e56df
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 51889b391a65..f0434528203f 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -63,6 +63,7 @@ _STRING = "string"_NULLABLE_STRING = "nullable_string"_INTEGER = "integer"_NULLABLE_INTEGER = "nullable_integer"+_NULLABLE_FLOAT = "nullable_float"_BOOLEAN = "boolean"@@ -86,6 +87,8 @@ def _column_expr(kind: str, index: int) -> ast.Expr:return ast.Call(name="toIntOrZero", args=[source])if kind == _NULLABLE_INTEGER:return ast.Call(name="accurateCastOrNull", args=[source, ast.Constant(value="Int64")])+ if kind == _NULLABLE_FLOAT:+ return ast.Call(name="accurateCastOrNull", args=[source, ast.Constant(value="Float64")])if kind == _BOOLEAN:return ast.Call(name="equals", args=[source, ast.Constant(value="true")])raise ValueError(f"Unknown information_schema column kind: {kind}")@@ -174,31 +177,42 @@ def _visible_table_names(database: "Database") -> list[str]:return [n for n in database.tables.resolve_visible_table_names() if not n.startswith("posthog.")]+# Per-column statistics surfaced into information_schema.columns: (null_fraction, min_value, max_value).+_ColumnStats = tuple[Optional[float], Optional[str], Optional[str]]++def _warehouse_metadata(team_id: Optional[int],-) -> tuple[dict[tuple[str, str], str], dict[str, Optional[int]], dict[str, Optional[int]]]:- """Lazily load warehouse semantic descriptions and row counts for the team.+) -> tuple[+ dict[tuple[str, str], str], dict[str, Optional[int]], dict[str, Optional[int]], dict[tuple[str, str], _ColumnStats]+]:+ """Lazily load warehouse semantic descriptions, row counts, and column statistics for the team.- Returns `(descriptions, row_counts, view_row_counts)`. Descriptions are keyed by+ Returns `(descriptions, row_counts, view_row_counts, column_stats)`. Descriptions are keyed by`(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- the SQL-editor schema agree.+ by warehouse table name, `view_row_counts` by saved-query (view) name. `column_stats` is keyed by+ `(table_id, column_name)` and carries `(null_fraction, min_value, max_value)` from the Delta-log+ profiling. 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 the SQL-editor schema agree."""descriptions: dict[tuple[str, str], str] = {}row_counts: dict[str, Optional[int]] = {}view_row_counts: dict[str, Optional[int]] = {}+ column_stats: dict[tuple[str, str], _ColumnStats] = {}if team_id is None:- return descriptions, row_counts, view_row_counts+ return descriptions, row_counts, view_row_counts, column_stats# Inline imports: keeps the products dependency off the hogql import path (avoids an import# cycle, since products import hogql) and off every non-information_schema query.from posthog.models.scoping import team_scope # noqa: PLC0415from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery- from products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415- from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation # noqa: PLC0415+ from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415+ DataWarehouseTable,+ WarehouseColumnAnnotation,+ WarehouseColumnStatistics,+ )try:with team_scope(team_id):@@ -230,13 +244,25 @@ def _warehouse_metadata(.values_list("name", "table__row_count")):view_row_counts[view_name] = row_count+ # Per-column profiling stats (keyed by table UUID + column, like descriptions). Only the+ # columns that have been profiled appear; everything else stays absent (NULL in the catalog).+ for (+ table_id,+ column_name,+ null_fraction,+ min_value,+ max_value,+ ) in WarehouseColumnStatistics.objects.values_list(+ "table_id", "column_name", "null_fraction", "min_value", "max_value"+ ):+ column_stats[(str(table_id), column_name)] = (null_fraction, min_value, max_value)except Exception:# Schema discovery must never fail a query because the warehouse metadata could not be read,# but log so a transient DB error can be told apart from a real bug in the fetch loop.logger.exception("information_schema: failed to load warehouse metadata", team_id=team_id)- return {}, {}, {}+ return {}, {}, {}, {}- return descriptions, row_counts, view_row_counts+ return descriptions, row_counts, view_row_counts, column_statsdef _unwrap(expr: ast.Expr) -> ast.Expr:@@ -325,6 +351,7 @@ _KIND_TO_CLICKHOUSE: dict[str, str] = {_NULLABLE_STRING: "Nullable(String)",_INTEGER: "Int64",_NULLABLE_INTEGER: "Nullable(Int64)",+ _NULLABLE_FLOAT: "Nullable(Float64)",# HogQL's BooleanDatabaseField maps to ClickHouse UInt8; Python bool serializes to it directly._BOOLEAN: "UInt8",}@@ -339,6 +366,8 @@ def _column_field(name: str, kind: str) -> DatabaseField:return IntegerDatabaseField(name=name, nullable=False)if kind == _NULLABLE_INTEGER:return IntegerDatabaseField(name=name, nullable=True)+ if kind == _NULLABLE_FLOAT:+ return FloatDatabaseField(name=name, nullable=True)if kind == _BOOLEAN:return BooleanDatabaseField(name=name, nullable=False)raise ValueError(f"Unknown information_schema column kind: {kind}")@@ -419,7 +448,9 @@ class _Introspection:self.allowed_tables = allowed_tablesself.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)+ self.descriptions, self.row_counts, self.view_row_counts, self.column_stats = _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]] = {}@@ -492,6 +523,14 @@ class _Introspection:return self.descriptions.get((str(table_id), column_name))return None+ def _column_stats(self, table: Table, table_type: str, column_name: str) -> _ColumnStats:+ """`(null_fraction, min_value, max_value)` for a warehouse column, or all-None otherwise."""+ if table_type == "data_warehouse":+ table_id = getattr(table, "table_id", None)+ if table_id:+ return self.column_stats.get((str(table_id), column_name), (None, None, None))+ return (None, None, None)+def collect(self) -> tuple[list[list[Any]], list[list[Any]], list[list[Any]]]:table_rows: list[list[Any]] = []column_rows: list[list[Any]] = []@@ -540,6 +579,7 @@ class _Introspection:if isinstance(field, DatabaseField):kind = "expression" if isinstance(field, ExpressionField) else "column"+ null_fraction, min_value, max_value = self._column_stats(table, table_type, qualified)column_rows.append([table_schema,@@ -551,6 +591,9 @@ class _Introspection:bool(field.array),kind,self._column_description(table, table_type, qualified, field),+ null_fraction,+ min_value,+ max_value,])ordinal += 1@@ -580,7 +623,20 @@ class _Introspection:elif isinstance(field, VirtualTable):# Surface nested virtual-table columns as `parent.child` columns.column_rows.append(- [table_schema, table_name, qualified, ordinal, "VirtualTable", False, False, "virtual_table", None]+ [+ table_schema,+ table_name,+ qualified,+ ordinal,+ "VirtualTable",+ False,+ False,+ "virtual_table",+ None,+ None,+ None,+ None,+ ])ordinal += 1ordinal = self._collect_fields(@@ -640,6 +696,9 @@ _COLUMNS_COLUMNS: list[tuple[str, str]] = [("is_array", _BOOLEAN),("field_kind", _STRING),("description", _NULLABLE_STRING),+ ("null_fraction", _NULLABLE_FLOAT),+ ("min_value", _NULLABLE_STRING),+ ("max_value", _NULLABLE_STRING),]_RELATIONSHIPS_COLUMNS: list[tuple[str, str]] = [@@ -720,7 +779,8 @@ class InformationSchemaTablesTable(LazyTable):class InformationSchemaColumnsTable(LazyTable):description: str = ("SQL-standard catalog of every column on every visible table; one row per column. Filter by "- "table_name to inspect a table's columns, their types, and descriptions."+ "table_name to inspect a table's columns, their types, descriptions, and (for data warehouse "+ "tables) profiling statistics: null_fraction, min_value, max_value.")fields: dict[str, FieldOrTable] = {"table_schema": _string_field(@@ -756,6 +816,31 @@ class InformationSchemaColumnsTable(LazyTable):"description": _string_field("description", nullable=True, description="Human/agent-facing description of what the column holds."),+ "null_fraction": FloatDatabaseField(+ name="null_fraction",+ nullable=True,+ description=(+ "Fraction of values that are NULL (0.0–1.0), from data warehouse column statistics. "+ "Use it to avoid or special-case null-heavy columns. NULL for non-warehouse tables and "+ "for warehouse columns not yet profiled."+ ),+ ),+ "min_value": _string_field(+ "min_value",+ nullable=True,+ description=(+ "Minimum value observed in this column (from the Delta-log statistics), as a string. "+ "Use it to bound range and time-window filters. NULL when unprofiled or not applicable."+ ),+ ),+ "max_value": _string_field(+ "max_value",+ nullable=True,+ description=(+ "Maximum value observed in this column (from the Delta-log statistics), as a string. "+ "Use it to bound range and time-window filters. NULL when unprofiled or not applicable."+ ),+ ),}def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.pyindex 66cab4653bd6..5f541498d35a 100644--- a/posthog/hogql/database/schema/test/test_information_schema.py+++ b/posthog/hogql/database/schema/test/test_information_schema.py@@ -20,6 +20,7 @@ from posthog.models.scoping import team_scopefrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTablefrom products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation+from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatisticsdef _field(name: str) -> ast.Field:@@ -130,7 +131,7 @@ class TestWarehouseMetadata(APIBaseTest):# rather than being clobbered by a dead row's stale value (which is what `.objects` returned).self._table("orders", 100)self._table("orders", 5, deleted=True)- _descriptions, row_counts, _view_row_counts = _warehouse_metadata(self.team.id)+ _descriptions, row_counts, _view_row_counts, _column_stats = _warehouse_metadata(self.team.id)assert row_counts["orders"] == 100def test_view_row_count_comes_from_the_backing_table(self):@@ -138,7 +139,7 @@ class TestWarehouseMetadata(APIBaseTest):DataWarehouseSavedQuery.objects.create(team=self.team, name="orders_view", query={"query": "SELECT 1"}, columns={}, table=backing)- _descriptions, _row_counts, view_row_counts = _warehouse_metadata(self.team.id)+ _descriptions, _row_counts, view_row_counts, _column_stats = _warehouse_metadata(self.team.id)assert view_row_counts["orders_view"] == 42def test_metadata_does_not_leak_other_teams_row_counts(self):@@ -147,7 +148,7 @@ class TestWarehouseMetadata(APIBaseTest):other_team = Team.objects.create(organization=self.organization, name="other")self._table("shared", 999, team=other_team)self._table("shared", 7)- _descriptions, row_counts, _view_row_counts = _warehouse_metadata(self.team.id)+ _descriptions, row_counts, _view_row_counts, _column_stats = _warehouse_metadata(self.team.id)assert row_counts["shared"] == 7def test_descriptions_are_keyed_by_table_id_not_name(self):@@ -169,7 +170,7 @@ class TestWarehouseMetadata(APIBaseTest):description="Unique order identifier.",description_source=WarehouseColumnAnnotation.DescriptionSource.USER_EDITED,)- descriptions, _row_counts, _view_row_counts = _warehouse_metadata(self.team.id)+ descriptions, _row_counts, _view_row_counts, _column_stats = _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@@ -356,6 +357,50 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):)assert columns[0][0] == "Stripe charge identifier (ch_...)."+ def test_warehouse_column_statistics_are_merged(self):+ # Per-column profiling stats are surfaced on information_schema.columns for warehouse tables,+ # keyed by table id + column (like descriptions). A warehouse column without stats stays NULL.+ credentials = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=self.team)+ table = DataWarehouseTable.objects.create(+ name="stripe_charges",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="https://bucket.s3/data/*",+ row_count=42,+ columns={+ "id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True},+ "amount": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True},+ },+ )+ with team_scope(self.team.id, canonical=True):+ WarehouseColumnStatistics.objects.create(+ team=self.team,+ table=table,+ column_name="id",+ null_fraction=0.25,+ min_value="ch_001",+ max_value="ch_999",+ has_min_max=True,+ )++ rows = (+ execute_hogql_query(+ """+ SELECT column_name, null_fraction, min_value, max_value+ FROM system.information_schema.columns+ WHERE table_name = 'stripe_charges'+ ORDER BY column_name+ """,+ team=self.team,+ ).results+ or []+ )+ by_column = {row[0]: list(row[1:]) for row in rows}+ assert by_column["id"] == [0.25, "ch_001", "ch_999"]+ # Profiled stats absent for this column → all NULL.+ assert by_column["amount"] == [None, None, None]+def test_ordinal_positions_are_unique_within_a_table(self):# `events` exposes nested virtual-table columns (e.g. `group_0.*`); their ordinals must# continue the parent table's numbering rather than restart at 1 and collide.diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex b86a914e934c..c7e4507e8168 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -5874,6 +5874,36 @@"schema_valid": true,"table": null,"type": "string"+ },+ "null_fraction": {+ "chain": null,+ "fields": null,+ "hogql_value": "null_fraction",+ "id": null,+ "name": "null_fraction",+ "schema_valid": true,+ "table": null,+ "type": "float"+ },+ "min_value": {+ "chain": null,+ "fields": null,+ "hogql_value": "min_value",+ "id": null,+ "name": "min_value",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "max_value": {+ "chain": null,+ "fields": null,+ "hogql_value": "max_value",+ "id": null,+ "name": "max_value",+ "schema_valid": true,+ "table": null,+ "type": "string"}},"id": "system.information_schema.columns",@@ -14261,6 +14291,36 @@"schema_valid": true,"table": null,"type": "string"+ },+ "null_fraction": {+ "chain": null,+ "fields": null,+ "hogql_value": "null_fraction",+ "id": null,+ "name": "null_fraction",+ "schema_valid": true,+ "table": null,+ "type": "float"+ },+ "min_value": {+ "chain": null,+ "fields": null,+ "hogql_value": "min_value",+ "id": null,+ "name": "min_value",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "max_value": {+ "chain": null,+ "fields": null,+ "hogql_value": "max_value",+ "id": null,+ "name": "max_value",+ "schema_valid": true,+ "table": null,+ "type": "string"}},"id": "system.information_schema.columns",