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(aio): allow saved views over posthog.ai_events (#61873)

Carlos Marchal7ca50e08c8f7
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index a08c32946f72..07e955094772 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -226,6 +226,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
def get_columns(self) -> dict[str, dict[str, Any]]:
from posthog.api.services.query import process_query_dict
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.hogql_queries.query_runner import ExecutionMode
query = self.query or {}
@@ -237,7 +238,8 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
if "kind" not in query and "query" in query:
query = {"kind": "HogQLQuery", **query}
- response = process_query_dict(self.team, query, execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):
+ response = process_query_dict(self.team, query, execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
result = getattr(response, "types", [])
if result is None or isinstance(result, int):
diff --git a/products/data_modeling/backend/models/modeling.py b/products/data_modeling/backend/models/modeling.py
index 10394029e5bd..9b37de220ff8 100644
--- a/products/data_modeling/backend/models/modeling.py
+++ b/products/data_modeling/backend/models/modeling.py
@@ -779,7 +779,12 @@ class DataWarehouseModelPathManager(models.Manager["DataWarehouseModelPath"]):
the transaction and clean them up.
"""
parents = get_parents_from_model_query(team, model_name, model_query)
- posthog_table_names = self.get_hogql_database(team).get_posthog_table_names()
+ # include_hidden surfaces `posthog.*`-namespaced tables (e.g. posthog.ai_events) so they
+ # resolve as parents here too — matching the create path's get_table()-based resolution.
+ database = self.get_hogql_database(team)
+ posthog_table_names = set(database.get_posthog_table_names()) | set(
+ database.get_posthog_table_names(include_hidden=True)
+ )
base_params = {
"team_id": team.pk,
diff --git a/products/data_warehouse/backend/models/test/test_modeling.py b/products/data_warehouse/backend/models/test/test_modeling.py
index e205255db780..0ff2f4d15257 100644
--- a/products/data_warehouse/backend/models/test/test_modeling.py
+++ b/products/data_warehouse/backend/models/test/test_modeling.py
@@ -179,6 +179,31 @@ class TestModelPath(BaseTest):
self.assertIn(["events", saved_query.id.hex], paths)
self.assertIn(["persons", saved_query.id.hex], paths)
+ def test_update_paths_for_posthog_namespaced_table_query(self):
+ """`posthog.*`-namespaced tables (e.g. ai_events) must resolve as valid model-path parents on
+ the UPDATE path too. `update_paths_from_query` keys off `get_posthog_table_names()`, which omits
+ namespaced tables — so re-saving/re-materializing a view over `posthog.ai_events` raised
+ UnknownParentError until the hidden table names were unioned in. (The create path already
+ resolves them via `get_table()`.)"""
+ query = "SELECT trace_id FROM posthog.ai_events"
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="my_model",
+ query={"query": query},
+ )
+
+ # Create path seeds the initial paths (it resolves namespaced tables via get_table()).
+ DataWarehouseModelPath.objects.create_from_saved_query(saved_query)
+
+ # Update path is hit whenever an existing view is re-saved or re-materialized.
+ DataWarehouseModelPath.objects.update_from_saved_query(saved_query)
+
+ # `posthog.ai_events` is stored as two ltree labels (LabelTreeField splits on "."), exactly
+ # as the create path stores it — the update path must converge on the same single path.
+ paths = [mp.path for mp in DataWarehouseModelPath.objects.filter(team=self.team, saved_query=saved_query)]
+ self.assertEqual(len(paths), 1)
+ self.assertIn(["posthog", "ai_events", saved_query.id.hex], paths)
+
def test_create_from_warehouse_table_old_notation_nodes_query(self):
"""Test creation of a model path from a query that reads from a managed source using old notation."""
diff --git a/products/data_warehouse/backend/models/test/test_saved_query.py b/products/data_warehouse/backend/models/test/test_saved_query.py
index 3c4db3a1e348..5ce52efd4477 100644
--- a/products/data_warehouse/backend/models/test/test_saved_query.py
+++ b/products/data_warehouse/backend/models/test/test_saved_query.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from types import SimpleNamespace
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -143,3 +144,34 @@ class TestRevertMaterialization(BaseTest):
mock_delete_schedule.assert_called_once()
self._assert_state_unchanged()
+
+
+class TestGetColumnsQueryTagging(BaseTest):
+ """get_columns infers types by executing the query via sync_execute, which requires product +
+ feature query tags (enforced as a hard error in DEBUG). Untagged, view creation over any table —
+ including ai_events — fails with UntaggedQueryError. The inference query must be tagged."""
+
+ @patch("posthog.api.services.query.process_query_dict")
+ def test_get_columns_tags_the_inference_query(self, mock_process_query_dict):
+ from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
+
+ captured: dict[str, object] = {}
+
+ def _capture(*args, **kwargs):
+ tags = get_query_tags()
+ captured["product"] = tags.product
+ captured["feature"] = tags.feature
+ return SimpleNamespace(types=[("trace_id", "String")])
+
+ mock_process_query_dict.side_effect = _capture
+
+ saved_query = DataWarehouseSavedQuery(
+ team=self.team,
+ name="my_view",
+ query={"query": "SELECT trace_id FROM posthog.ai_events"},
+ )
+ columns = saved_query.get_columns()
+
+ assert captured["product"] == Product.WAREHOUSE
+ assert captured["feature"] == Feature.DATA_MODELING
+ assert columns == {"trace_id": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True}}
diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.py
index 0f41fd073087..780398bdc8cb 100644
--- a/products/warehouse_sources/backend/models/util.py
+++ b/products/warehouse_sources/backend/models/util.py
@@ -136,6 +136,9 @@ def clean_type(column_type: str) -> str:
# Replace newline characters followed by empty space
column_type = re.sub(r"\n\s+", "", column_type)
+ if column_type.startswith("LowCardinality("):
+ column_type = column_type.replace("LowCardinality(", "")[:-1]
+
if column_type.startswith("Nullable("):
column_type = column_type.replace("Nullable(", "")[:-1]
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 4d7fe53adacc..bf4915942bc4 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -7,6 +7,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.models.util import CLICKHOUSE_HOGQL_MAPPING, clean_type
@pytest.mark.parametrize(
@@ -23,3 +24,20 @@ def test_db_table_preserved_across_split(model: type[Model], expected_db_table:
"""The split moved these models to a new Django app via SeparateDatabaseAndState;
the `posthog_*` table names must remain unchanged or prod reads break silently."""
assert model._meta.db_table == expected_db_table
+
+
+ "clickhouse_type,expected",
+ [
+ ("String", "String"),
+ ("Nullable(String)", "String"),
+ ("LowCardinality(String)", "String"),
+ ("LowCardinality(Nullable(String))", "String"),
+ ],
+)
+def test_clean_type_unwraps_low_cardinality(clickhouse_type: str, expected: str) -> None:
+ """`ai_events` exposes LowCardinality columns (event, model, provider, ...). clean_type must
+ unwrap LowCardinality so the ClickHouse->HogQL mapping lookup resolves instead of KeyError-ing."""
+ cleaned = clean_type(clickhouse_type)
+ assert cleaned == expected
+ assert cleaned in CLICKHOUSE_HOGQL_MAPPING