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.

fix(posthog-ai): generate schema reference tables from the HogQL catalog (#84279)

Sam Pennington3704d350af01
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index 369e6042b79a..5e4c54ffb083 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -2146,6 +2146,29 @@ def direct_connection_information_schema_node() -> TableNode:
return node
+def static_column_rows() -> list[list[Any]]:
+ """`columns` rows for the statically-defined schema, resolved without a team or any database
+ access, so build-time tooling can render exactly what `system.information_schema.columns`
+ serves at query time.
+
+ Team-scoped inputs (warehouse tables, semantic-layer annotations, column statistics) resolve
+ empty at `team_id=None` — the static schema is all that's left, which is the point.
+
+ Row layout matches `_Introspection.column_rows()`:
+ `[table_schema, table_name, column_name, ordinal, data_type, is_nullable, is_array, field_kind,
+ description, null_fraction, min_value, max_value]`.
+ """
+ # Deferred: `Database` imports the schema package, so a module-level import would cycle.
+ from posthog.hogql.context import HogQLContext # noqa: PLC0415
+ from posthog.hogql.database.database import Database # noqa: PLC0415
+
+ database = Database()
+ # `enable_select_queries` lets expression columns be typed by the value they evaluate to
+ # (`deleted` → `Integer`) instead of falling back to the generic "Expression".
+ context = HogQLContext(team_id=None, database=database, enable_select_queries=True)
+ return _Introspection(database, context).column_rows()
+
+
def disable_data_catalog(info_schema: TableNode) -> None:
info_schema.children.pop("metrics", None)
info_schema.children.pop("certifications", None)
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
index 147d51ebc1d1..ea29a31bd6ea 100755
--- a/products/posthog_ai/scripts/build_skills.py
+++ b/products/posthog_ai/scripts/build_skills.py
@@ -454,12 +454,14 @@ class SkillRenderer:
from products.posthog_ai.scripts.hogql_example import render_hogql_example
from products.posthog_ai.scripts.hogql_functions import hogql_functions
from products.posthog_ai.scripts.pydantic_schema import pydantic_schema
+ from products.posthog_ai.scripts.schema_columns import schema_columns
self.env = _create_jinja_env(
pydantic_schema=pydantic_schema,
render_hogql_example=render_hogql_example,
hogql_functions=hogql_functions,
audit_constants=audit_constants,
+ schema_columns=schema_columns,
)
def render(self, source_file: Path) -> str:
diff --git a/products/posthog_ai/scripts/schema_columns/__init__.py b/products/posthog_ai/scripts/schema_columns/__init__.py
new file mode 100644
index 000000000000..d0ca6210535d
--- /dev/null
+++ b/products/posthog_ai/scripts/schema_columns/__init__.py
@@ -0,0 +1,58 @@
+"""Render schema reference tables for skill docs straight from the HogQL catalog.
+
+The `models-*.md` references used to carry hand-written column lists copied from the Django
+models. HogQL exposes a curated subset of those columns under different names and types, so the
+docs advertised columns the executor rejects (`system.insights.is_sample`, `created_by`, ...) and
+agents burned a failed query plus a schema-discovery query to recover. Rendering from
+`static_column_rows` — the same collector behind `system.information_schema.columns` — means the
+reference and the executor cannot disagree.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from functools import lru_cache
+
+_HEADER = "Column | Type | Nullable | Description"
+
+
+# Not `@frozen` from `posthog.dataclasses`: importing it runs `posthog/__init__`, and every helper
+# in this directory keeps that off the module import path, resolving posthog lazily when called.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class _SchemaColumn:
+ name: str
+ data_type: str
+ nullable: bool
+ description: str
+
+
+@lru_cache(maxsize=1)
+def _columns_by_table() -> dict[str, list[_SchemaColumn]]:
+ from posthog.hogql.database.schema.information_schema import static_column_rows
+
+ by_table: dict[str, list[_SchemaColumn]] = {}
+ for row in static_column_rows():
+ by_table.setdefault(row[1], []).append(
+ _SchemaColumn(name=row[2], data_type=row[4], nullable=bool(row[5]), description=row[8] or "")
+ )
+ return by_table
+
+
+def schema_columns(table_name: str) -> str:
+ """Return the markdown column table for `table_name` (e.g. `system.insights`).
+
+ Raises on an unknown table so a renamed or removed table fails the skill build instead of
+ silently shipping an empty reference.
+ """
+ columns = _columns_by_table().get(table_name)
+ if not columns:
+ available = ", ".join(sorted(t for t in _columns_by_table() if t.startswith("system."))[:8])
+ raise ValueError(f"No columns found for HogQL table {table_name!r}. Known system tables include: {available}…")
+
+ lines = [_HEADER]
+ for column in columns:
+ nullable = "NULL" if column.nullable else "NOT NULL"
+ # Descriptions are prose and may wrap; collapse so one column stays on one row.
+ description = " ".join(column.description.split())
+ lines.append(f"`{column.name}` | {column.data_type} | {nullable} | {description}".rstrip())
+ return "\n".join(lines)
diff --git a/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py b/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py
new file mode 100644
index 000000000000..26ba940c4289
--- /dev/null
+++ b/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py
@@ -0,0 +1,22 @@
+from __future__ import annotations
+
+import pytest
+
+from products.posthog_ai.scripts.schema_columns import schema_columns
+
+
+def test_unknown_table_raises() -> None:
+ with pytest.raises(ValueError, match="system.not_a_table"):
+ schema_columns("system.not_a_table")
+
+
+def test_renders_only_columns_hogql_exposes() -> None:
+ rendered = schema_columns("system.insights")
+
+ assert "`team_id` | Integer | NOT NULL" in rendered
+ # `deleted` is an expression column over the hidden `_deleted`; the alias is what resolves.
+ assert "`deleted` | Integer | NOT NULL" in rendered
+ assert "`_deleted`" not in rendered
+ # Django-model fields HogQL does not expose, which the docs used to advertise.
+ for absent in ("is_sample", "derived_name", "filters_hash", "refreshing"):
+ assert absent not in rendered
diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
index 5ceb01ca1248..8b06f893d821 100644
--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md
+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
@@ -51,7 +51,9 @@ Curating the catalog — creating or approving metrics, certifying sources, revi
## Data Schema
-Schema reference for PostHog's core system models, organized by domain:
+Schema reference for PostHog's core system models, organized by domain.
+
+Every column table below is generated from the live HogQL catalog, so it lists exactly what `execute-sql` resolves. `system.*` tables expose a curated subset of each Django model, so a field returned by a REST tool such as `insight-get` is not necessarily queryable — trust these tables over the REST response shape.
- [Activity logs](./references/models-activity-logs.md)
- [Actions](./references/models-actions.md)
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md b/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md
deleted file mode 100644
index 6664f8deb9b6..000000000000
--- a/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# Dashboards, Tiles & Insights
-
-## Dashboard (`system.dashboards`)
-
-Dashboards are collections of insights that provide a unified view of analytics data.
-
-### Columns
-
-Column | Type | Nullable | Description
-`id` | integer | NOT NULL | Primary key (auto-generated)
-`name` | varchar(400) | NULL | Dashboard name
-`description` | text | NOT NULL | Dashboard description
-`pinned` | boolean | NOT NULL | Whether dashboard is pinned
-`created_at` | timestamp with tz | NOT NULL | Creation timestamp
-`deleted` | boolean | NOT NULL | Soft delete flag
-`last_accessed_at` | timestamp with tz | NULL | Last access timestamp
-`filters` | jsonb | NOT NULL | Dashboard-level filters applied to all insights
-`creation_mode` | varchar(16) | NOT NULL | How dashboard was created: `default`, `template`, `duplicate`, `unlisted`
-`restriction_level` | smallint | NOT NULL | Access restriction: `21` (everyone can edit), `37` (only collaborators)
-`created_by_id` | integer | NULL | Creator user ID
-`variables` | jsonb | NULL | Dashboard variables for dynamic filtering
-`breakdown_colors` | jsonb | NULL | Custom breakdown color assignments
-`data_color_theme_id` | integer | NULL | Color theme ID
-`last_refresh` | timestamp with tz | NULL | Last refresh timestamp
-
-### Important Notes
-
-- The default manager excludes soft-deleted dashboards (`deleted=True`)
-- `creation_mode='unlisted'` dashboards are hidden from general lists (used for product dashboards like AI observability)
-- Use `filters` to store dashboard-level date ranges and property filters
-
----
-
-## Insight (`system.insights`)
-
-Insights are saved analytics queries that visualize data.
-
-### Columns
-
-Column | Type | Nullable | Description
-`id` | integer | NOT NULL | Primary key (auto-generated)
-`name` | varchar(400) | NULL | User-defined insight name
-`derived_name` | varchar(400) | NULL | Auto-generated name from query
-`description` | varchar(400) | NULL | Insight description
-`filters` | jsonb | NOT NULL | Filter configuration (legacy, prefer `query`)
-`filters_hash` | varchar(400) | NULL | Hash for caching
-`query` | jsonb | NULL | Modern HogQL query definition (preferred)
-`query_metadata` | jsonb | NULL | Extracted query metadata for indexing
-`order` | integer | NULL | Display order
-`deleted` | boolean | NOT NULL | Soft delete flag
-`saved` | boolean | NOT NULL | Whether insight is saved (vs temporary)
-`created_at` | timestamp with tz | NULL | Creation timestamp
-`refreshing` | boolean | NOT NULL | Whether currently refreshing
-`is_sample` | boolean | NOT NULL | Whether this is sample data
-`short_id` | varchar(12) | NOT NULL | Unique short identifier for URLs
-`favorited` | boolean | NOT NULL | Whether favorited by user
-`refresh_attempt` | integer | NULL | Number of refresh attempts
-`last_modified_at` | timestamp with tz | NOT NULL | Last modification timestamp
-`updated_at` | timestamp with tz | NOT NULL | Auto-updated timestamp
-`created_by_id` | integer | NULL | Creator user ID
-`last_modified_by_id` | integer | NULL | Last modifier user ID
-
-### Key Relationships
-
-- **Survey**: Can be linked to surveys via `system.surveys.linked_insight_id`
-
-### Important Notes
-
-- `short_id` is unique per team and used in URLs: `/insights/{short_id}`
-- Only insights with `saved=True` appear in the insights list
-- The default manager excludes soft-deleted insights
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md.j2 b/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md.j2
new file mode 100644
index 000000000000..704b8b7d4c87
--- /dev/null
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-dashboards-insights.md.j2
@@ -0,0 +1,30 @@
+# Dashboards, Tiles & Insights
+
+## Dashboard (`system.dashboards`)
+
+Dashboards are collections of insights that provide a unified view of analytics data.
+
+### Columns
+
+{{ schema_columns('system.dashboards') }}
+
+### Important Notes
+
+- Soft-deleted dashboards are excluded by default; filter with `NOT deleted`
+- Use `filters` to store dashboard-level date ranges and property filters
+
+---
+
+## Insight (`system.insights`)
+
+Insights are saved analytics queries that visualize data.
+
+### Columns
+
+{{ schema_columns('system.insights') }}
+
+### Important Notes
+
+- `short_id` is unique per team and used in URLs: `/insights/{short_id}`
+- Only saved insights appear in the insights list; filter with `saved`
+- Soft-deleted insights are excluded by default; filter with `NOT deleted`