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(data-modeling): surface saved query view descriptions in information_schema (#67415)

Thiago Salvatore306bc3d04b17
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index f0434528203f..fc38d1893133 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -184,30 +184,41 @@ _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]], dict[tuple[str, str], _ColumnStats]
+ dict[tuple[str, str], str],
+ dict[str, Optional[int]],
+ dict[str, Optional[int]],
+ dict[tuple[str, str], _ColumnStats],
+ dict[tuple[str, str], str],
]:
"""Lazily load warehouse semantic descriptions, row counts, and column statistics for the team.
- 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. `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.
+ Returns `(descriptions, row_counts, view_row_counts, column_stats, view_descriptions)`.
+ `descriptions` are physical-table annotations 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. `column_stats` is keyed by `(table_id, column_name)`
+ and carries `(null_fraction, min_value, max_value)` from the Delta-log profiling.
+ `view_descriptions` are data-modelling saved-query (view) annotations keyed by
+ `(saved_query_id, column_name)`, `""` denoting the view-level description. 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] = {}
+ view_descriptions: dict[tuple[str, str], str] = {}
if team_id is None:
- return descriptions, row_counts, view_row_counts, column_stats
+ return descriptions, row_counts, view_row_counts, column_stats, view_descriptions
# 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: PLC0415
- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+ from products.data_modeling.backend.facade.models import ( # noqa: PLC0415
+ DataWarehouseSavedQuery,
+ DataWarehouseSavedQueryColumnAnnotation,
+ )
from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415
DataWarehouseTable,
WarehouseColumnAnnotation,
@@ -224,6 +235,13 @@ def _warehouse_metadata(
"table_id", "column_name", "description"
):
descriptions[(str(table_id), column_name)] = description
+ # View (saved-query) annotations, keyed by the saved-query UUID — the `SavedQuery` HogQL
+ # object carries that same id, so the catalog lookup matches. `column_name=""` is the
+ # view-level description.
+ for saved_query_id, column_name, description in DataWarehouseSavedQueryColumnAnnotation.objects.values_list(
+ "saved_query_id", "column_name", "description"
+ ):
+ view_descriptions[(str(saved_query_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 —
@@ -260,9 +278,9 @@ def _warehouse_metadata(
# 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, column_stats
+ return descriptions, row_counts, view_row_counts, column_stats, view_descriptions
def _unwrap(expr: ast.Expr) -> ast.Expr:
@@ -448,9 +466,13 @@ class _Introspection:
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, self.column_stats = _warehouse_metadata(
- context.team_id
- )
+ (
+ self.descriptions,
+ self.row_counts,
+ self.view_row_counts,
+ self.column_stats,
+ self.view_descriptions,
+ ) = _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]] = {}
@@ -511,6 +533,10 @@ class _Introspection:
table_id = getattr(table, "table_id", None)
if table_type == "data_warehouse" and table_id:
return self.descriptions.get((str(table_id), ""))
+ # Views carry their saved-query UUID on the `SavedQuery` HogQL object as `id`.
+ view_id = getattr(table, "id", None)
+ if table_type == "view" and view_id:
+ return self.view_descriptions.get((str(view_id), ""))
return None
def _column_description(
@@ -521,6 +547,9 @@ class _Introspection:
table_id = getattr(table, "table_id", None)
if table_type == "data_warehouse" and table_id:
return self.descriptions.get((str(table_id), column_name))
+ view_id = getattr(table, "id", None)
+ if table_type == "view" and view_id:
+ return self.view_descriptions.get((str(view_id), column_name))
return None
def _column_stats(self, table: Table, table_type: str, column_name: str) -> _ColumnStats:
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index 6a2a348c39a6..32cdd1b8a562 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -17,7 +17,10 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models import Team
from posthog.models.scoping import team_scope
-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_modeling.backend.facade.models import (
+ DataWarehouseSavedQuery,
+ DataWarehouseSavedQueryColumnAnnotation,
+)
from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation
from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics
@@ -131,7 +134,9 @@ 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, _column_stats = _warehouse_metadata(self.team.id)
+ _descriptions, row_counts, _view_row_counts, _column_stats, _view_descriptions = _warehouse_metadata(
+ self.team.id
+ )
assert row_counts["orders"] == 100
def test_view_row_count_comes_from_the_backing_table(self):
@@ -139,7 +144,9 @@ 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, _column_stats = _warehouse_metadata(self.team.id)
+ _descriptions, _row_counts, view_row_counts, _column_stats, _view_descriptions = _warehouse_metadata(
+ self.team.id
+ )
assert view_row_counts["orders_view"] == 42
def test_metadata_does_not_leak_other_teams_row_counts(self):
@@ -148,9 +155,32 @@ 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, _column_stats = _warehouse_metadata(self.team.id)
+ _descriptions, row_counts, _view_row_counts, _column_stats, _view_descriptions = _warehouse_metadata(
+ self.team.id
+ )
assert row_counts["shared"] == 7
+ def test_metadata_does_not_leak_other_teams_view_descriptions(self):
+ # View annotations are team-scoped via TeamScopedManager; lock that in so a future switch to
+ # `.unscoped()` (or an explicit cross-team fetch) can't leak another team's view descriptions
+ # into this team's catalog, which the AI reads.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_view = DataWarehouseSavedQuery.objects.create(
+ team=other_team, name="orders_view", query={"query": "SELECT 1"}, columns={}
+ )
+ with team_scope(other_team.id, canonical=True):
+ DataWarehouseSavedQueryColumnAnnotation.objects.create(
+ team=other_team,
+ saved_query=other_view,
+ column_name="",
+ description="Other team's private view.",
+ description_source=DataWarehouseSavedQueryColumnAnnotation.DescriptionSource.USER_EDITED,
+ )
+ _descriptions, _row_counts, _view_row_counts, _column_stats, view_descriptions = _warehouse_metadata(
+ self.team.id
+ )
+ assert view_descriptions == {}
+
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.
@@ -170,7 +200,9 @@ class TestWarehouseMetadata(APIBaseTest):
description="Unique order identifier.",
description_source=WarehouseColumnAnnotation.DescriptionSource.USER_EDITED,
)
- descriptions, _row_counts, _view_row_counts, _column_stats = _warehouse_metadata(self.team.id)
+ descriptions, _row_counts, _view_row_counts, _column_stats, _view_descriptions = _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
@@ -432,8 +464,8 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
def test_saved_query_view_columns_appear_with_types(self):
# The view's columns (built from the model's `columns` JSONField via `hogql_definition`) must be
- # enumerated with their HogQL types — that's the surface a later phase attaches column descriptions
- # to. Guards both the field enumeration and the JSONField→HogQL type mapping for views.
+ # enumerated with their HogQL types. Guards both the field enumeration and the JSONField→HogQL
+ # type mapping for views.
self._create_saved_query_view(name="revenue_view")
response = execute_hogql_query(
"""
@@ -446,6 +478,50 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
assert columns["order_id"] == "String"
assert columns["amount"] == "Integer"
+ def test_saved_query_view_descriptions_are_merged_from_annotations(self):
+ # View- and column-level descriptions stored as DataWarehouseSavedQueryColumnAnnotation must
+ # surface in the catalog so PostHog AI can read them. Guards the metadata loader plus the
+ # `table_type == "view"` resolution branch: a regression (loader dropped, wrong key, or branch
+ # gated on the wrong table_type) makes descriptions silently vanish from information_schema.
+ view = self._create_saved_query_view(name="revenue_view")
+ with team_scope(self.team.id, canonical=True):
+ DataWarehouseSavedQueryColumnAnnotation.objects.create(
+ team=self.team,
+ saved_query=view,
+ column_name="",
+ description="Revenue per order, one row per completed order.",
+ description_source=DataWarehouseSavedQueryColumnAnnotation.DescriptionSource.USER_EDITED,
+ )
+ DataWarehouseSavedQueryColumnAnnotation.objects.create(
+ team=self.team,
+ saved_query=view,
+ column_name="amount",
+ description="Order revenue in cents.",
+ description_source=DataWarehouseSavedQueryColumnAnnotation.DescriptionSource.AI_GENERATED,
+ )
+
+ table_rows = (
+ execute_hogql_query(
+ "SELECT description FROM system.information_schema.tables WHERE table_name = 'revenue_view'",
+ team=self.team,
+ ).results
+ or []
+ )
+ assert len(table_rows) == 1
+ assert table_rows[0][0] == "Revenue per order, one row per completed order."
+
+ column_rows = (
+ execute_hogql_query(
+ "SELECT column_name, description FROM system.information_schema.columns WHERE table_name = 'revenue_view'",
+ team=self.team,
+ ).results
+ or []
+ )
+ by_column = {row[0]: row[1] for row in column_rows}
+ assert by_column["amount"] == "Order revenue in cents."
+ # An unannotated column stays NULL rather than borrowing another column's description.
+ assert by_column["order_id"] is None
+
def test_materialized_saved_query_view_reports_backing_table_row_count(self):
# A materialized view stays classified as a view but carries the row count of its backing table.
# Exercises the `table_type == "view"` branch of row-count resolution end-to-end (the unit test on