: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
perf(insights): build the hogql database once per insight run (#88183)
Sandy Spicer3ab4fee30dd9
diff --git a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.tsindex 0c27939d2174..6196c39b7b75 100644--- a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts+++ b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts@@ -63,6 +63,7 @@ const EDITABLE_INSTANCE_SETTINGS = ['CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS','CLICKHOUSE_KILL_SWITCH_FULL_TEAMS','CLICKHOUSE_HEDGED_APP_QUERIES',+ 'HOGQL_SHARED_INSIGHT_DATABASE_ENABLED',]// Generated by kea-typegen. Update if you're an agent, ignore if you're human.diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 816191b2b577..632944d3a840 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -615,7 +615,13 @@ class Database(BaseModel):# warehouse table is accessed (see get_table / _ensure_foreign_keys_built)._deferred_foreign_key_tables: list[Any] = []_foreign_keys_built: bool = True- _foreign_keys_building: bool = False+ # Thread ident of the thread currently running the build pass, for recursion detection. A+ # database can be shared by several query threads (e.g. trends series), so the guard must+ # distinguish same-thread re-entry from a concurrent thread that has to wait.+ _foreign_keys_building_thread: Optional[int] = None+ # Per-instance so unrelated databases built concurrently in one process never contend; nothing+ # copies or pickles a Database, so the lock is safe to hold as instance state.+ _foreign_keys_build_lock: Any = None# Lowercased, because Snowflake nodes resolve case-insensitively and a query may name a table with# casing that differs from the canonical catalog name._foreign_key_trigger_names: Optional[set[str]] = None@@ -650,7 +656,8 @@ class Database(BaseModel):self._data_warehouse_sync_warnings = {}self._deferred_foreign_key_tables = []self._foreign_keys_built = True- self._foreign_keys_building = False+ self._foreign_keys_building_thread = None+ self._foreign_keys_build_lock = threading.Lock()self._foreign_key_trigger_names = Noneself._deferred_overridable_expression_field_ids = set()self._serialization_errors: dict[str, str] = {} # table_key -> error_message@@ -721,31 +728,38 @@ class Database(BaseModel):The full graph is built in a single pass (not just the accessed table) so reverse joins andfield precedence match the eager path exactly. Resolving a foreign-key target re-enters- get_table, so `_foreign_keys_building` guards that recursion rather than the built flag — the- work stays pending until the pass finishes, so a mid-pass failure doesn't leave a half-wired- graph behind. Callers that swallow resolution errors retry on their next access instead.+ get_table, so `_foreign_keys_building_thread` guards that recursion rather than the built+ flag — the work stays pending until the pass finishes, so a mid-pass failure doesn't leave a+ half-wired graph behind. Callers that swallow resolution errors retry on their next access+ instead. A database can be shared by concurrent query threads, so a thread that isn't the+ builder blocks on the lock and observes the finished graph rather than a half-wired one.Saved expressions were applied at build time (before this runs), so foreign keys are allowedto replace a colliding saved-expression field — preserving the eager "saved expressions nevershadow a join field" invariant. Only fields saved expressions created are overridable; theid/timestamp mappings event modifiers write stay put, as they did in the eager order."""- if self._foreign_keys_built or self._foreign_keys_building:+ if self._foreign_keys_built or self._foreign_keys_building_thread == threading.get_ident():return- self._foreign_keys_building = True- try:- with tracer.start_as_current_span("warehouse_foreign_keys"):- for hogql_table, warehouse_table_model in self._deferred_foreign_key_tables:- add_postgres_foreign_key_lazy_joins(- hogql_table=hogql_table,- warehouse_table=warehouse_table_model,- database=self,- schemas=_get_active_external_data_schemas(warehouse_table_model),- overridable_expression_field_ids=self._deferred_overridable_expression_field_ids,- )- finally:- self._foreign_keys_building = False- self._foreign_keys_built = True- self._deferred_foreign_key_tables = []+ with self._foreign_keys_build_lock:+ # Re-check under the lock: another thread may have finished the build while this one+ # waited. mypy's flow analysis cannot see cross-thread mutation.+ if self._foreign_keys_built:+ return # type: ignore[unreachable]+ self._foreign_keys_building_thread = threading.get_ident()+ try:+ with tracer.start_as_current_span("warehouse_foreign_keys"):+ for hogql_table, warehouse_table_model in self._deferred_foreign_key_tables:+ add_postgres_foreign_key_lazy_joins(+ hogql_table=hogql_table,+ warehouse_table=warehouse_table_model,+ database=self,+ schemas=_get_active_external_data_schemas(warehouse_table_model),+ overridable_expression_field_ids=self._deferred_overridable_expression_field_ids,+ )+ finally:+ self._foreign_keys_building_thread = None+ self._foreign_keys_built = True+ self._deferred_foreign_key_tables = []def _suggest_table_names(self, name: str, *, limit: int = 3) -> list[str]:"""Return up to `limit` close matches for a mistyped table name.diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex eb921d1dffa9..5cc68f3aa979 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -65,8 +65,13 @@ def to_printed_hogql(modifiers: "HogQLQueryModifiers | None" = None,*,bypass_warehouse_access_control: bool = False,+ database: Database | None = None,) -> str:- """Prints the HogQL query without mutating the node"""+ """Prints the HogQL query without mutating the node.++ Pass `database` to reuse an already-built schema instead of building a new one — building the+ full database is the dominant cost of printing on teams with many warehouse tables.+ """return prepare_and_print_ast(clone_expr(query),dialect="hogql",@@ -75,6 +80,7 @@ def to_printed_hogql(enable_select_queries=True,modifiers=create_default_modifiers_for_team(team, modifiers),bypass_warehouse_access_control=bypass_warehouse_access_control,+ database=database,),pretty=True,)[0]diff --git a/posthog/hogql_queries/ai/actors_property_taxonomy_query_runner.py b/posthog/hogql_queries/ai/actors_property_taxonomy_query_runner.pyindex fce9fcbc7f2d..ba98a321bc36 100644--- a/posthog/hogql_queries/ai/actors_property_taxonomy_query_runner.py+++ b/posthog/hogql_queries/ai/actors_property_taxonomy_query_runner.py@@ -8,7 +8,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Product, tags_context@@ -29,7 +28,7 @@ class ActorsPropertyTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunnerdef _calculate(self):query = self.to_query()- hogql = to_printed_hogql(query, self.team)+ hogql = self.response_hogql(query)with tags_context(product=Product.MAX_AI):response = execute_hogql_query(@@ -37,6 +36,7 @@ class ActorsPropertyTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunnerquery=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py b/posthog/hogql_queries/ai/event_taxonomy_query_runner.pyindex 457f53d176a8..33d2d86208c9 100644--- a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py+++ b/posthog/hogql_queries/ai/event_taxonomy_query_runner.py@@ -9,9 +9,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings-from posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import action_to_exprfrom posthog.clickhouse.query_tagging import Product, tags_context@@ -46,7 +44,7 @@ class EventTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[EventTaxdef _calculate(self):query = self.to_query()- hogql = to_printed_hogql(query, self.team)+ hogql = self.response_hogql(query)with tags_context(product=Product.MAX_AI):self.paginator.execute_hogql_query(@@ -57,11 +55,7 @@ class EventTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[EventTaxtimings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,- context=HogQLContext(- team_id=self.team.pk,- user=self.user,- use_new_events_schema=self._use_new_events_schema,- ),+ context=self.build_hogql_context(use_new_events_schema=self._use_new_events_schema),)results: list[EventTaxonomyItem] = []diff --git a/posthog/hogql_queries/ai/team_taxonomy_query_runner.py b/posthog/hogql_queries/ai/team_taxonomy_query_runner.pyindex 4ee34f46b039..1f1e94f591b6 100644--- a/posthog/hogql_queries/ai/team_taxonomy_query_runner.py+++ b/posthog/hogql_queries/ai/team_taxonomy_query_runner.py@@ -8,7 +8,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.parser import parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.clickhouse.query_tagging import Product, tags_contextfrom posthog.hogql_queries.ai.utils import TaxonomyCacheMixin@@ -47,7 +46,7 @@ class TeamTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[TeamTaxondef _calculate(self):query = self.to_query()- hogql = to_printed_hogql(query, self.team)+ hogql = self.response_hogql(query)with tags_context(product=Product.MAX_AI):self.paginator.execute_hogql_query(@@ -55,6 +54,7 @@ class TeamTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[TeamTaxonquery=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/ai/vector_search_query_runner.py b/posthog/hogql_queries/ai/vector_search_query_runner.pyindex 3dcef8cb8074..cc2838ad3370 100644--- a/posthog/hogql_queries/ai/vector_search_query_runner.py+++ b/posthog/hogql_queries/ai/vector_search_query_runner.py@@ -7,7 +7,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Product, tags_context@@ -27,7 +26,7 @@ class VectorSearchQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[VectorSeaquery = self.to_query()with self.timings.measure("to_printed_hogql"):- hogql = to_printed_hogql(query, self.team)+ hogql = self.response_hogql(query)with tags_context(product=Product.MAX_AI), self.timings.measure("execute_hogql_query"):response = execute_hogql_query(@@ -35,6 +34,7 @@ class VectorSearchQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[VectorSeaquery=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.pyindex 1fd1acbbcc1d..7f556908a52a 100644--- a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py@@ -24,9 +24,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContext-from posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimings@@ -249,19 +247,14 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationResponsdef _calculate_internal(self) -> CorrelationCalculation:query = self.to_query()- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = execute_hogql_query(query_type="FunnelsQuery",query=query,team=self.team,user=self.user,- context=HogQLContext(- team_id=self.team.pk,- user=self.user,- use_new_events_schema=self._use_new_events_schema,- ),+ context=self.build_hogql_context(use_new_events_schema=self._use_new_events_schema),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py b/posthog/hogql_queries/insights/funnels/funnels_query_runner.pyindex a03b0dbbe10a..80c1271910ee 100644--- a/posthog/hogql_queries/insights/funnels/funnels_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnels_query_runner.py@@ -27,7 +27,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettings, LimitContext-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimings@@ -285,14 +284,14 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):timings = []# TODO: can we get this from execute_hogql_query as well?- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = execute_hogql_query(query_type="FunnelsQuery",query=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=effective_timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel.py b/posthog/hogql_queries/insights/funnels/test/test_funnel.pyindex cde9e76ce6a9..10ab3515a90a 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel.py@@ -13,6 +13,7 @@ from posthog.test.base import (create_person_id_override_by_distinct_id,snapshot_clickhouse_queries,)+from unittest.mock import patchfrom django.conf import settingsfrom django.test import override_settings@@ -47,6 +48,7 @@ from posthog.schema import (StepOrderValue,)+from posthog.hogql.database.database import Databasefrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.api.instance_settings import get_instance_setting@@ -899,6 +901,24 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):self.assertEqual(results[1]["name"], "paid")self.assertEqual(results[1]["count"], 1)+ def test_builds_database_once_per_run(self):+ query = FunnelsQuery(+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-14"),+ series=[+ EventsNode(event="user signed up", name="user signed up"),+ EventsNode(event="paid", name="paid"),+ ],+ )++ _create_person(distinct_ids=["user_1"], team_id=self.team.pk)+ _create_event(team=self.team, event="user signed up", distinct_id="user_1", timestamp="2020-01-02T14:00:00Z")++ with patch.object(Database, "create_for", wraps=Database.create_for) as mock_create_for:+ results = FunnelsQueryRunner(query=query, team=self.team).calculate().results++ assert len(results) == 2+ assert mock_create_for.call_count == 1+def test_basic_funnel_with_person_id_override_properties_joined_modifier_and_person_breakdown(self):query = FunnelsQuery(breakdownFilter=BreakdownFilter(diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.pyindex 1ec5f8b9a0f9..ab1fa3884d92 100644--- a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py+++ b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py@@ -22,7 +22,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.hogql.query import execute_hogql_query@@ -172,14 +171,14 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):def _calculate(self) -> LifecycleQueryResponse:query = self.to_query()- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = execute_hogql_query(query_type="LifecycleQuery",query=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/posthog/hogql_queries/insights/retention/retention_query_runner.pyindex 901191ac527a..848ca911c495 100644--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/retention_query_runner.py@@ -28,7 +28,6 @@ from posthog.hogql.constants import (get_breakdown_limit_for_context,)from posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import entity_to_expr, property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimings@@ -651,14 +650,14 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):def _calculate(self) -> RetentionQueryResponse:query = self.to_query()- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = execute_hogql_query(query_type="RetentionQuery",query=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py b/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.pyindex 62fc354b7949..ce97e2dc7a0f 100644--- a/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py@@ -95,6 +95,7 @@ class BoxPlotTrendsQueryRunner(TrendsQueryRunner):team=self.team,timings=self.timings,modifiers=self.modifiers,+ database=self.shared_database,)all_boxplot_data: list[BoxPlotDatum] = []@@ -110,6 +111,7 @@ class BoxPlotTrendsQueryRunner(TrendsQueryRunner):query=boxplot_query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.pyindex ab3b913ea2a2..c423f0f825fe 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py@@ -61,6 +61,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.query import execute_hogql_query@@ -455,6 +456,20 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual("$pageview", response.results[0]["label"])+ def test_multi_series_builds_database_once(self):+ self._create_test_events()++ with patch.object(Database, "create_for", wraps=Database.create_for) as mock_create_for:+ response = self._run_trends_query(+ self.default_date_from,+ self.default_date_to,+ IntervalType.DAY,+ [EventsNode(event="$pageview"), EventsNode(event="$pageleave")],+ )++ assert len(response.results) == 2+ assert mock_create_for.call_count == 1+@parameterized.expand([("custom_name set via rename modal", EventsNode(event="$pageview", custom_name="Renamed"), "Renamed"),diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.pyindex 283a3bdab87c..9bf35d923f47 100644--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py@@ -375,7 +375,10 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):def _calculate(self):queries = self.to_queries()- response_hogql = get_response_hogql(queries, team=self.team, timings=self.timings, modifiers=self.modifiers)++ response_hogql = get_response_hogql(+ queries, team=self.team, timings=self.timings, modifiers=self.modifiers, database=self.shared_database+ )res_matrix: list[list[Any] | Any | None] = [None] * len(queries)timings_matrix: list[list[QueryTiming] | None] = [None] * (2 + len(queries))@@ -403,6 +406,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):timings=timings,modifiers=self.modifiers,limit_context=self.limit_context,+ context=self.build_hogql_context(),)timings_matrix[index + 1] = response.timingsdiff --git a/posthog/hogql_queries/insights/utils/utils.py b/posthog/hogql_queries/insights/utils/utils.pyindex 8f9735eae8d4..1127c2e8df0d 100644--- a/posthog/hogql_queries/insights/utils/utils.py+++ b/posthog/hogql_queries/insights/utils/utils.py@@ -14,6 +14,7 @@ from posthog.schema import ()from posthog.hogql import ast+from posthog.hogql.database.database import Databasefrom posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.timings import HogQLTimings@@ -75,6 +76,7 @@ def get_response_hogql(team: Team,timings: HogQLTimings,modifiers: Optional[HogQLQueryModifiers] = None,+ database: Optional[Database] = None,) -> str:if len(queries) == 0:return ""@@ -84,5 +86,8 @@ def get_response_hogql(# This only prints the query for the response payload — it never executes — and access to the# underlying warehouse tables is already enforced on the insight's executed query. Bypass warehouse# access control so building the printer's database doesn't fail closed in userless contexts.+ # When the caller already built a database for the executed query, `database` reuses it here.with timings.measure("printing_hogql_for_response"):- return to_printed_hogql(response_hogql_query, team, modifiers, bypass_warehouse_access_control=True)+ return to_printed_hogql(+ response_hogql_query, team, modifiers, bypass_warehouse_access_control=True, database=database+ )diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 893a5c6edc16..3f47743b1b6d 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -1,3 +1,4 @@+import threadingfrom abc import ABC, abstractmethodfrom collections.abc import Callable, Sequencefrom datetime import UTC, datetime, timedelta@@ -104,7 +105,7 @@ from posthog.hogql.constants import LimitContextfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.modifiers import create_default_modifiers_for_user-from posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogqlfrom posthog.hogql.query import create_default_modifiers_for_teamfrom posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.warehouse_warnings import accumulator_scope@@ -144,6 +145,7 @@ from posthog.hogql_queries.validation.validation import (run_validation_rules,)from posthog.models import Team, User+from posthog.models.instance_setting import get_instance_settingfrom posthog.models.team import WeekStartDayfrom posthog.models.team.event_retention import events_retention_months_for_teamfrom posthog.query_cache import QueryCache, count_query_cache_hit@@ -1648,6 +1650,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):self.team = teamself.user = userself.timings = timings or HogQLTimings()+ self._shared_database: Optional[Database] = None+ self._shared_database_build_lock = threading.Lock()self.limit_context = limit_context or LimitContext.QUERYself.query_id = query_idself.workload = workload@@ -1682,9 +1686,47 @@ class QueryRunner(ABC, Generic[Q, R, CR]):def _on_user_changed(self) -> None:"""Hook called by run() when self.user is updated after construction.- Subclasses can override to rebuild any user-dependent state (e.g. a- cached HogQLContext / Database that was created with a stale user)."""- pass+ Drops the lazily built shared database so the next access rebuilds it for the new+ user. Subclasses that override this to rebuild their own user-dependent state (e.g.+ a cached HogQLContext / Database) must call super()._on_user_changed()."""+ self._shared_database = None++ @property+ def shared_database(self) -> Database:+ """One Database for every query this runner executes and for the response SQL printer.++ Building the database is the dominant compile cost on teams with many warehouse+ tables, and it is identical for every query in one run. Built lazily so cache hits+ never pay for it; dropped by _on_user_changed so access control follows the user."""+ if not get_instance_setting("HOGQL_SHARED_INSIGHT_DATABASE_ENABLED"):+ # Kill switch: build per access so query threads never share schema state. No timings+ # measure here because concurrent threads reach this path and HogQLTimings is not+ # thread-safe.+ return Database.create_for(team=self.team, user=self.user, modifiers=self.modifiers)+ if self._shared_database is None:+ # Concurrent query threads (funnels compare mode) can first-touch this property at the+ # same time. The lock makes the build run once, and keeps the measure on the single+ # builder thread because HogQLTimings is not thread-safe.+ with self._shared_database_build_lock:+ if self._shared_database is None:+ with self.timings.measure("build_shared_database"):+ self._shared_database = Database.create_for(+ team=self.team,+ user=self.user,+ modifiers=self.modifiers,+ timings=self.timings,+ )+ return self._shared_database++ def build_hogql_context(self, **kwargs: Any) -> HogQLContext:+ """Context for execute_hogql_query calls this runner makes, wired to the shared database."""+ return HogQLContext(team_id=self.team.pk, user=self.user, database=self.shared_database, **kwargs)++ def response_hogql(self, query: ast.SelectQuery | ast.SelectSetQuery) -> str:+ """Display-only HogQL for the response payload (never executed).++ Prints against the shared database so the printer does not build a second one."""+ return to_printed_hogql(query, self.team, database=self.shared_database)@propertydef query_type(self) -> Any:@@ -3012,6 +3054,7 @@ class QueryRunnerWithHogQLContext(AnalyticsQueryRunner[AR]):def _on_user_changed(self) -> None:if self.hogql_context.user is self.user:return+ super()._on_user_changed()self._build_hogql_context_for_user(self.user)@propertydiff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 519fb8544c7c..75dd99ffdfc3 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -1,3 +1,5 @@+import time+import threadingfrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal, Optionalfrom zoneinfo import ZoneInfo@@ -63,6 +65,7 @@ from posthog.hogql_queries.query_runner import (shared_insights_execution_mode,)from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.models.instance_setting import override_instance_configfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.team.team import Team, WeekStartDay@@ -200,6 +203,66 @@ class TestQueryRunner(BaseTest):self.assertEqual(runner.query, TheTestQuery(some_attr="bla"))+ def test_shared_database_is_reused_and_rebuilt_on_user_change(self):+ TestQueryRunner = self.setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)++ first = runner.shared_database+ assert runner.shared_database is first++ runner.user = self.user+ runner._on_user_changed()+ assert runner.shared_database is not first++ def test_shared_database_first_touch_is_thread_safe(self):+ TestQueryRunner = self.setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)++ build_count = 0++ def slow_build(*args: Any, **kwargs: Any) -> Any:+ nonlocal build_count+ build_count += 1+ # Holds the first build open past the second thread's None check, so an+ # implementation without the lock deterministically builds twice.+ time.sleep(0.05)+ return mock.MagicMock()++ barrier = threading.Barrier(2)+ results: list[Any] = [None, None]+ errors: list[Exception] = []++ def first_touch(index: int) -> None:+ try:+ barrier.wait()+ results[index] = runner.shared_database+ except Exception as e:+ errors.append(e)++ with mock.patch.object(Database, "create_for", side_effect=slow_build):+ threads = [threading.Thread(target=first_touch, args=(index,)) for index in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert errors == []+ assert build_count == 1+ assert results[0] is results[1]+ timing_keys = [key for key in runner.timings.to_dict() if "build_shared_database" in key]+ assert timing_keys == ["./build_shared_database"]++ def test_shared_database_kill_switch_disables_sharing(self):+ TestQueryRunner = self.setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)++ with override_instance_config("HOGQL_SHARED_INSIGHT_DATABASE_ENABLED", False):+ first = runner.shared_database+ second = runner.shared_database++ assert first is not second+ assert runner.shared_database is runner.shared_database+def test_init_with_query_dict(self):TestQueryRunner = self.setup_test_query_runner_class()diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex c67252ec0c52..60e157c9dada 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -19,6 +19,12 @@ CONSTANCE_CONFIG = {"Number of weeks recording performance events will be kept before removing them (for all projects). Storing performance events for a shorter timeframe can help reduce Clickhouse disk usage.",int,),+ "HOGQL_SHARED_INSIGHT_DATABASE_ENABLED": (+ get_from_env("HOGQL_SHARED_INSIGHT_DATABASE_ENABLED", True, type_cast=str_to_bool),+ "Whether insight query runners share one HogQL database across execution, response printing, "+ "and series threads. Disable to fall back to building a database per call.",+ bool,+ ),"MATERIALIZED_COLUMNS_ENABLED": (get_from_env("MATERIALIZED_COLUMNS_ENABLED", True, type_cast=str_to_bool),"Whether materialized columns should be created or used at query time.",@@ -339,6 +345,7 @@ CONSTANCE_CONFIG = {}SETTINGS_ALLOWING_API_OVERRIDE = (+ "HOGQL_SHARED_INSIGHT_DATABASE_ENABLED","RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS","AUTO_START_ASYNC_MIGRATIONS","AGGREGATE_BY_DISTINCT_IDS_TEAMS",diff --git a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.pyindex 8f47593b4630..4812bdeb35f7 100644--- a/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/paths/paths_query_runner.py@@ -24,7 +24,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettings, LimitContextfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.timings import HogQLTimings@@ -887,14 +886,14 @@ class PathsQueryRunner(AnalyticsQueryRunner[PathsQueryResponse]):def _calculate(self) -> PathsQueryResponse:query = self.to_query()- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = execute_hogql_query(query_type="PathsQuery",query=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py b/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.pyindex 91fa768a7ff9..19af30e3ce8d 100644--- a/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py@@ -27,7 +27,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettingsfrom posthog.hogql.parser import parse_expr, parse_select-from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query@@ -901,6 +900,7 @@ class PathsV2QueryRunner(AnalyticsQueryRunner[PathsV2QueryResponse]):query=query,team=self.team,user=self.user,+ context=self.build_hogql_context(),timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,@@ -912,8 +912,7 @@ class PathsV2QueryRunner(AnalyticsQueryRunner[PathsV2QueryResponse]):def _calculate(self) -> PathsV2QueryResponse:query = self.to_query()- # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.- hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)+ hogql = self.response_hogql(query)response = self._execute(query)assert response.results is not None