: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(hogql): record warehouse tables a query reads on query executed (#112528)
Anna Szell862e2b2132f4
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex c25c1d3a8ba1..de0a2dd345e1 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -627,6 +627,10 @@ class HogQLQueryExecutor:if adapter is None:raise InternalHogQLError(f"No direct SQL adapter registered for engine: {source.direct_engine}")+ stats = query_stats.get_active()+ if stats is not None:+ stats.add_direct_source(str(source.id))+query_tags = get_query_tags()cancellation_token = (build_direct_query_cancellation_token(query_tags.client_query_id, str(query_tags.celery_task_id))@@ -934,6 +938,11 @@ class HogQLQueryExecutor:)stats = query_stats.get_active()+ if stats is not None:+ stats.add_reads(+ warehouse_table_ids=self.context.referenced_warehouse_table_ids,+ saved_query_ids=self.context.referenced_saved_query_ids,+ )# The rows are read back per thread after the run, so a run ClickHouse stops is still# recorded with what it read, and a series running in another thread is not charged here.query_stats.reset_last_rows_read()diff --git a/posthog/hogql/query_stats.py b/posthog/hogql/query_stats.pyindex e743f7e97d7e..64e8522ac455 100644--- a/posthog/hogql/query_stats.py+++ b/posthog/hogql/query_stats.py@@ -61,6 +61,10 @@ class QueryStats:# References only, filled by the executor, so the job can explain each execution without rerunning it.executions: list[RecordedExecution] = field(default_factory=list, repr=False, compare=False)workloads: set[str] = field(default_factory=set, repr=False, compare=False)+ warehouse_table_ids: set[str] = field(default_factory=set, repr=False, compare=False)+ saved_query_ids: set[str] = field(default_factory=set, repr=False, compare=False)+ # Queries on a direct connection never reach ClickHouse or bind warehouse tables, so the source is the only trace.+ direct_source_ids: set[str] = field(default_factory=set, repr=False, compare=False)def add(self, *, rows_read: int, duration_ms: float, lookup: bool = False, workload: str | None = None) -> None:with self.lock:@@ -73,6 +77,15 @@ class QueryStats:if workload is not None:self.workloads.add(workload)+ def add_reads(self, *, warehouse_table_ids: set[str], saved_query_ids: set[str]) -> None:+ with self.lock:+ self.warehouse_table_ids |= warehouse_table_ids+ self.saved_query_ids |= saved_query_ids++ def add_direct_source(self, source_id: str) -> None:+ with self.lock:+ self.direct_source_ids.add(source_id)+def record_execution(self,*,diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 007bcc0a5593..c819883010bf 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -32,6 +32,7 @@ from posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.escape_sql import escape_postgres_identifierfrom posthog.hogql.printer.postgres import PostgresPrinterfrom posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.query_stats import query_stats_scopefrom posthog.models import Team@@ -1095,10 +1096,14 @@ class TestDirectPostgresQuery(APIBaseTest):send_raw_query=True,)- with patch.object(HogQLQueryExecutor, "_prepare_execution") as mock_prepare_execution:+ with (+ patch.object(HogQLQueryExecutor, "_prepare_execution") as mock_prepare_execution,+ query_stats_scope() as stats,+ ):response = executor.execute()self.assertEqual(response.results, [(1,)])+ self.assertEqual(stats.direct_source_ids, {str(source.id)})self.assertEqual(response.clickhouse, "SELECT 1 AS value")self.assertEqual(response.columns, ["value"])self.assertIsNone(response.hogql)diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 145834c4ce6c..d6f8f3d5f4ff 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -2668,6 +2668,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"clickhouse_duration_ms": cached_query_scan.duration_ms if cached_query_scan else None,"clickhouse_workload": None,"clickhouse_query_count": None,+ "warehouse_tables_referenced": None,+ "saved_queries_referenced": None,+ "direct_connection_source_ids": None,**cache_tracking_props,**phase_times,}@@ -2922,6 +2925,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"clickhouse_duration_ms": round(query_stats.duration_ms),"clickhouse_workload": query_stats.workload(),"clickhouse_query_count": query_stats.query_count,+ "warehouse_tables_referenced": sorted(query_stats.warehouse_table_ids),+ "saved_queries_referenced": sorted(query_stats.saved_query_ids),+ "direct_connection_source_ids": sorted(query_stats.direct_source_ids),"query_scan_triggered": scan_skip is None,"query_scan_skipped_reason": scan_skip,**phase_times,diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 3e58bc8f1ca0..c324d5b88597 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -187,6 +187,10 @@ _QUERY_SCAN_FLAG_LOG_ONLY = QueryScanFlag(def _calculate_recording_clickhouse_stats(_self):record(rows_read=12, duration_ms=34.0, workload="ONLINE")+ stats = get_active()+ assert stats is not None+ stats.add_reads(warehouse_table_ids={"table-b", "table-a"}, saved_query_ids={"view-a"})+ stats.add_direct_source("source-a")return TheTestBasicQueryResponse(results=[])@@ -915,6 +919,12 @@ class TestQueryRunner(BaseTest):assert fresh_props["cache_hit"] is Falseassert hit_props["cache_hit"] is True+ assert fresh_props["warehouse_tables_referenced"] == []+ assert hit_props["warehouse_tables_referenced"] is None+ assert fresh_props["saved_queries_referenced"] == []+ assert hit_props["saved_queries_referenced"] is None+ assert fresh_props["direct_connection_source_ids"] == []+ assert hit_props["direct_connection_source_ids"] is Noneassert fresh_props["query_hash"] == hit_props["query_hash"]assert fresh_props["runtime_hash"] == hit_props["runtime_hash"]@@ -935,6 +945,9 @@ class TestQueryRunner(BaseTest):assert props["clickhouse_rows_read"] == 12assert props["clickhouse_query_count"] == 1assert props["clickhouse_workload"] == "ONLINE"+ assert props["warehouse_tables_referenced"] == ["table-a", "table-b"]+ assert props["saved_queries_referenced"] == ["view-a"]+ assert props["direct_connection_source_ids"] == ["source-a"]@parameterized.expand([diff --git a/products/data_modeling/backend/test/test_saved_query_tagging.py b/products/data_modeling/backend/test/test_saved_query_tagging.pyindex be91fc1a2bc5..d86c843dc3a7 100644--- a/products/data_modeling/backend/test/test_saved_query_tagging.py+++ b/products/data_modeling/backend/test/test_saved_query_tagging.py@@ -12,6 +12,7 @@ from posthog.schema import HogQLQuery, HogQLQueryModifiersfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.query_stats import query_stats_scopefrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context@@ -147,10 +148,16 @@ class TestSavedQueryTagging(APIBaseTest):def test_execution_tags_the_views_and_tables_the_resolver_bound(self, _name: str, query: str, views: list[str], tables: list[str], direct: list[str]) -> None:- with tags_context(product=Product.WAREHOUSE, feature=Feature.QUERY), self.captured_tags() as captured:+ with (+ tags_context(product=Product.WAREHOUSE, feature=Feature.QUERY),+ self.captured_tags() as captured,+ query_stats_scope() as stats,+ ):with suppress(_Captured):self.executor(query).execute()self.assertEqual(captured, [(self.ids(*views), self.ids(*tables), self.ids(*direct))])+ self.assertEqual(sorted(stats.warehouse_table_ids), self.ids(*tables) or [])+ self.assertEqual(sorted(stats.saved_query_ids), self.ids(*views) or [])def test_context_reuse_and_cte_shadowing_do_not_tag(self) -> None:context = HogQLContext(team=self.team, database=Database.create_for(team=self.team))