: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-modeling): tag queries with the saved queries they read (#101024)
Jovan Sakoviceae0d341c077
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 603898e3463d..bfb7dc48abde 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -519,6 +519,7 @@ class QueryTags(BaseModel):trend_volume_display: Optional[str] = Nonetable_id: Optional[uuid.UUID] = Nonewarehouse_query: Optional[bool] = None+ saved_query_ids: Optional[list[str]] = Nonetrend_volume_type: Optional[str] = Nonediff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex b07864b07a2d..71941a2a518a 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -116,6 +116,7 @@ class HogQLContext:# Data warehouse sync warnings collected while resolving warehouse tables referenced by the query.# Keyed by (table_id, schema_name) to dedupe when a table is referenced multiple times.data_warehouse_sync_warnings: dict[tuple[str, str], "DataWarehouseSyncWarning"] = field(default_factory=dict)+ referenced_saved_query_ids: set[str] = field(default_factory=set)# Resources with object-level access restrictions referenced by the query, collected while printing# system tables. A set dedupes when several system tables share an access scope (e.g. system.dashboardsdiff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex ba7aa41d11ee..a73fe912e7ae 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -2298,6 +2298,11 @@ class Database(BaseModel):self_managed_warehouse_tables: TableNode = TableNode()views: TableNode = TableNode()warehouse_tables_to_process: list[tuple[Table, DataWarehouseTable]] = []+ saved_query_ids_by_table = {+ saved_query.table_id: str(saved_query.pk)+ for saved_query in sources.saved_queries+ if saved_query.table_id is not None+ }with timings.measure("data_warehouse_saved_query", emit_span=True):for saved_query in sources.saved_queries:@@ -2404,6 +2409,8 @@ class Database(BaseModel):with timings.measure(f"table_{table.name}"):s3_table = table.hogql_definition(modifiers)+ if isinstance(s3_table, S3Table):+ s3_table.saved_query_id = saved_query_ids_by_table.get(table.pk)sync_warnings = get_warehouse_sync_warnings(table, now=sync_warnings_now)if sync_warnings:diff --git a/posthog/hogql/database/s3_table.py b/posthog/hogql/database/s3_table.pyindex 5cf1db1e113f..e42539cadd2a 100644--- a/posthog/hogql/database/s3_table.py+++ b/posthog/hogql/database/s3_table.py@@ -270,6 +270,8 @@ class S3Table(FunctionCallTable):# Used to attribute query execution back to the source that was synced, for usage telemetry.external_data_source_id: Optional[str] = Nonesource_type: Optional[str] = None+ # Set when this table backs a materialized saved query, so a query that reads the table is attributed to the view.+ saved_query_id: Optional[str] = Nonedef to_printed_hogql(self):return escape_hogql_identifier(self.name)diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex f36426111755..b99f7dcb9e90 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -694,6 +694,7 @@ class HogQLQueryExecutor:raisedef _prepare_execution(self, *, embedded_select: bool = False) -> _PreparedExecution:+ self.context.referenced_saved_query_ids.clear()self._parse_query()if embedded_select:@@ -785,6 +786,7 @@ class HogQLQueryExecutor:has_joins="JOIN" in self.clickhouse_sql,has_json_operations="JSONExtract" in self.clickhouse_sql or "JSONHas" in self.clickhouse_sql,hogql_features=hogql_features,+ saved_query_ids=sorted(self.context.referenced_saved_query_ids) or None,timings=timings_dict,modifiers=({k: v for k, v in self.modifiers.model_dump().items() if v is not None} if self.modifiers else {}diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 58a97d612819..7f703f132f30 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -1423,6 +1423,11 @@ class Resolver(CloningVisitor):raisedatabase_table = opaque_table+ if isinstance(database_table, SavedQuery):+ self.context.referenced_saved_query_ids.add(database_table.id)+ elif isinstance(database_table, S3Table) and database_table.saved_query_id is not None:+ self.context.referenced_saved_query_ids.add(database_table.saved_query_id)+if self.dialect == "trino":database_table = lower_trino_table(database_table, self.context)diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex dca0ba30693f..cdb52884a2e7 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -26,7 +26,10 @@ from posthog.hogql.database.direct_redshift_table import DirectRedshiftTablefrom posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.direct_trino_table import DirectTrinoTablefrom posthog.hogql.database.models import FieldOrTable, SavedQuery-from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable+from posthog.hogql.database.s3_table import (+ DataWarehouseTable as HogQLDataWarehouseTable,+ S3Table,+)from posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel@@ -535,7 +538,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,DirectTrinoTable,]:if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:- return self.table.hogql_definition(modifiers)+ table = self.table.hogql_definition(modifiers)+ if isinstance(table, S3Table):+ table.saved_query_id = str(self.id)+ return tablequery = self.query or {}if not isinstance(query, dict) or "query" not in query:diff --git a/products/data_modeling/backend/test/test_saved_query_tagging.py b/products/data_modeling/backend/test/test_saved_query_tagging.pynew file mode 100644index 000000000000..7f831c873039--- /dev/null+++ b/products/data_modeling/backend/test/test_saved_query_tagging.py@@ -0,0 +1,114 @@+from collections.abc import Iterator+from contextlib import contextmanager, suppress+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.schema import HogQLQuery, HogQLQueryModifiers++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.query import HogQLQueryExecutor++from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context++from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable+++class _Captured(Exception):+ pass+++class TestSavedQueryTagging(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="demand_view",+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS id, now() AS created_at, 'd' AS distinct_id"},+ columns={"id": "Int64", "created_at": "DateTime", "distinct_id": "String"},+ )+ credentials = DataWarehouseCredential.objects.create(team=self.team, access_key="fake", access_secret="fake")+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name="demand_matview",+ format="Parquet",+ credential=credentials,+ url_pattern="https://example.com/data/*.parquet",+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "schema_valid": True}},+ )+ self.matview = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="demand_matview",+ query={"kind": "HogQLQuery", "query": "SELECT id FROM demand_view"},+ columns={"id": "Int64"},+ table=table,+ is_materialized=True,+ )++ @contextmanager+ def captured_tags(self) -> Iterator[list[list[str] | None]]:+ captured: list[list[str] | None] = []++ def execute(*args: Any, **kwargs: Any) -> Any:+ captured.append(get_query_tags().saved_query_ids)+ raise _Captured()++ with patch("posthog.hogql.query.sync_execute", side_effect=execute):+ yield captured++ def executor(self, query: str, context: HogQLContext | None = None) -> HogQLQueryExecutor:+ return HogQLQueryExecutor(+ query=query,+ team=self.team,+ modifiers=HogQLQueryModifiers(useMaterializedViews=True),+ context=context or HogQLContext(team=self.team),+ )++ @parameterized.expand(+ [+ ("plain_view", "SELECT id FROM demand_view", "view"),+ ("materialized_view_backing_table", "SELECT id FROM demand_matview", "matview"),+ ("no_saved_query", "SELECT 1", None),+ ]+ )+ def test_execution_tags_the_saved_queries_the_resolver_bound(self, _name: str, query: str, expected: str | None):+ with tags_context(product=Product.WAREHOUSE, feature=Feature.QUERY), self.captured_tags() as captured:+ with suppress(_Captured):+ self.executor(query).execute()+ self.assertEqual(captured, [[str(getattr(self, expected).pk)] if expected else None])++ def test_context_reuse_and_cte_shadowing_do_not_tag(self) -> None:+ context = HogQLContext(team=self.team, database=Database.create_for(team=self.team))+ self.executor("SELECT id FROM demand_view", context).generate_clickhouse_sql()+ with tags_context(product=Product.WAREHOUSE, feature=Feature.QUERY), self.captured_tags() as captured:+ with suppress(_Captured):+ self.executor("WITH demand_view AS (SELECT 2 AS id) SELECT id FROM demand_view", context).execute()+ self.assertEqual(captured, [None])++ def run_query_api(self) -> None:+ self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {"query": HogQLQuery(query="SELECT id FROM demand_view").model_dump()},+ )++ def run_endpoint(self) -> None:+ self.client.post(+ f"/api/environments/{self.team.id}/endpoints/",+ {"name": "demand_view_feed", "query": {"kind": "HogQLQuery", "query": "SELECT id FROM demand_view"}},+ format="json",+ )+ self.client.post(f"/api/environments/{self.team.id}/endpoints/demand_view_feed/run/", {}, format="json")++ @parameterized.expand([("query_api",), ("endpoint",)])+ def test_every_entry_point_carries_the_tag(self, entry_point: str) -> None:+ with self.captured_tags() as captured:+ with suppress(Exception):+ getattr(self, f"run_{entry_point}")()+ self.assertTrue(captured, f"{entry_point} never reached ClickHouse")+ for saved_query_ids in captured:+ self.assertIn(str(self.view.pk), saved_query_ids or [])diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.pyindex 32f7a88eda39..1067da477802 100644--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py@@ -10,6 +10,7 @@ from posthog.test.base import (flush_persons_and_events,snapshot_clickhouse_queries,)+from unittest.mock import patchfrom django.test import override_settings@@ -35,9 +36,10 @@ from posthog.schema import (from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_team-from posthog.hogql.query import execute_hogql_query+from posthog.hogql.query import execute_hogql_query, sync_executefrom posthog.hogql.timings import HogQLTimings+from posthog.clickhouse.query_tagging import get_query_tagsfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.instance_setting import override_instance_config@@ -308,6 +310,22 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):assert set(response.columns).issubset({"date", "total"})return response.results[0][1][0]+ def test_trends_over_a_view_tags_the_saved_query(self):+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery++ real_sync_execute = sync_execute+ captured: list[list[str] | None] = []++ def spy(*args, **kwargs):+ captured.append(get_query_tags().saved_query_ids)+ return real_sync_execute(*args, **kwargs)++ with patch("posthog.hogql.query.sync_execute", side_effect=spy):+ self._avg_view_setup("avg")++ saved_query = DataWarehouseSavedQuery.objects.get(team=self.team, name="saved_view")+ assert captured[-1] == [str(saved_query.pk)]+def test_trends_view_avg(self):assert self._avg_view_setup("avg") == 3.5