: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(experiments): improve performance for session_context request by reducing builds of HogQL database (#73103)
Marcel Poelker897b862c5fbf
diff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.pyindex 573d7b6d0f2a..4a1c57de3b9f 100644--- a/products/experiments/backend/metric_events.py+++ b/products/experiments/backend/metric_events.py@@ -25,9 +25,12 @@ from posthog.schema import (ExperimentMeanMetric,ExperimentRatioMetric,ExperimentRetentionMetric,+ HogQLQueryModifiers,)from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.errors import BaseHogQLErrorfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query@@ -54,6 +57,32 @@ MAX_SCANNED_METRICS = 50MetricSourceNode = EventsNode | ActionsNode+@dataclass(frozen=True)+class SharedHogQLDatabase:+ """A HogQL virtual database built once per request and shared across that request's+ scans, bundled with the modifiers it was built with.++ Sharing the database is sound only while every scan treats it as read-only — the+ session-context scans run against it concurrently from a thread pool. HogQL mutates a+ database at query time in exactly two cases: `system.information_schema` queries register+ hidden external tables on it (`_rows_select` in+ posthog/hogql/database/schema/information_schema.py), and direct-connection queries make+ the executor rebuild it. Scans sharing one must therefore stick to plain table reads;+ everything here reads only `events`. The modifiers travel with the database because the+ schema depends on them (person-on-events mode changes the events table's person fields):+ every query against the shared database must execute with these modifiers, never its own.+ """++ database: Database+ modifiers: HogQLQueryModifiers++ def fresh_context(self, team: Team, user: User) -> HogQLContext:+ """A per-query context carrying the shared database, so `execute_hogql_query` reuses+ it instead of building its own. Contexts accumulate per-query state during printing+ and must never be shared between queries — the database can be."""+ return HogQLContext(team_id=team.pk, user=user, database=self.database)++@dataclass(frozen=True)class MetricEventSource:"""An experiment metric resolved to the concrete event/action sources it counts."""@@ -173,6 +202,7 @@ def scan_session_for_metric_events(session_id: str,window_start: datetime,window_end: datetime,+ shared_hogql: SharedHogQLDatabase | None = None,) -> list[MetricHit]:"""The metrics with >=1 matching event in the session, sorted by first occurrence.@@ -189,6 +219,11 @@ def scan_session_for_metric_events(source dedupe only narrows the query, it must not let a metric-heavy experiment emit anunbounded hit list by piling metrics onto one source. `user` threads through to HogQL forproperty-level access control — metric source nodes can carry property filters.++ `shared_hogql` optionally carries a prebuilt virtual database (session_context builds+ one shared across all its scans) — constructing it dominates query wall time on teams with+ a large warehouse schema, so callers that already hold one should pass it in, along with+ the modifiers it was built with."""names_by_uuid: dict[str, str] = {}# Metric uuids grouped by identical source nodes: identical sources compile to identical@@ -285,7 +320,13 @@ def scan_session_for_metric_events(]),)- response = execute_hogql_query(query, team=team, user=user)+ # execute_hogql_query treats a passed context as fully caller-owned, so only build one when+ # there is a shared database to carry; otherwise let the executor construct its default.+ extra_kwargs: dict[str, HogQLContext | HogQLQueryModifiers] = {}+ if shared_hogql is not None:+ extra_kwargs["context"] = shared_hogql.fresh_context(team, user)+ extra_kwargs["modifiers"] = shared_hogql.modifiers+ response = execute_hogql_query(query, team=team, user=user, **extra_kwargs)# Aggregation without GROUP BY always yields exactly one row; a metric with no matching# events shows count 0 there (and an epoch minIf), so the count guards the timestamps.diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex da3472a9b6b0..0774d697627b 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -36,7 +36,9 @@ import pydanticfrom posthog.schema import ExperimentEventExposureConfig, ExperimentExposureCriteriafrom posthog.hogql import ast+from posthog.hogql.database.database import Databasefrom posthog.hogql.errors import BaseHogQLError+from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query@@ -54,6 +56,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (from products.experiments.backend.metric_events import (MetricEventSource,MetricHit,+ SharedHogQLDatabase,resolve_metric_events,scan_session_for_metric_events,)@@ -195,6 +198,28 @@ def _compute_session_experiment_context(# No overlapping experiment defines variants, so nothing could surface a variant seen.return []+ # Every scan below goes through HogQL, and constructing the virtual database dominates this+ # endpoint's wall time on teams with a large warehouse schema — several seconds per query,+ # paid once per query, while ClickHouse itself answers in well under a second. Build the+ # database once here and share it across all the scans, including across the thread pool+ # below. Sound only while every scan sticks to plain table reads — SharedHogQLDatabase+ # documents the two query shapes that mutate a database at query time, and+ # test_uncached_request_shares_one_readonly_hogql_database pins that these scans don't.+ # The build modifiers travel with the database so every scan queries the schema it was+ # built for; no scan may pass its own modifiers. Postgres foreign-key lazy joins are+ # skipped — the single most expensive build step, and these queries only ever read the+ # events table.+ hogql_modifiers = create_default_modifiers_for_team(team)+ shared_hogql = SharedHogQLDatabase(+ database=Database.create_for(+ team=team,+ user=user,+ modifiers=hogql_modifiers,+ build_postgres_foreign_keys=False,+ ),+ modifiers=hogql_modifiers,+ )+# Flag evaluations are variant evidence for every experiment — the replay shows exactly# what the session was served, whatever the exposure criteria say — and double as the# exposure moment for experiments with the default criteria shape.@@ -202,6 +227,7 @@ def _compute_session_experiment_context(_query_flag_evaluations,team,user,+ shared_hogql,session_id,window_start,window_end,@@ -216,6 +242,7 @@ def _compute_session_experiment_context(_query_exposure_event_branches,team,user,+ shared_hogql,session_id,window_start,window_end,@@ -223,7 +250,7 @@ def _compute_session_experiment_context()candidate_keys = {experiment.feature_flag.key for experiment in candidates}query_stamped = partial(- _query_stamped_flag_properties, team, user, session_id, candidate_keys, window_start, window_end+ _query_stamped_flag_properties, team, user, shared_hogql, session_id, candidate_keys, window_start, window_end)# The three scans are independent given the pre-rescue candidate set (only the rescue@@ -262,7 +289,9 @@ def _compute_session_experiment_context(rescued_keys = evidenced_keys - candidate_keysif rescued_keys:candidates += list(overlapping.filter(feature_flag__key__in=sorted(rescued_keys)))- stamped.update(_query_stamped_flag_properties(team, user, session_id, rescued_keys, window_start, window_end))+ stamped.update(+ _query_stamped_flag_properties(team, user, shared_hogql, session_id, rescued_keys, window_start, window_end)+ )surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]] = []for experiment in candidates:@@ -313,6 +342,7 @@ def _compute_session_experiment_context(session_id=session_id,window_start=window_start,window_end=window_end,+ shared_hogql=shared_hogql,)}except Exception:@@ -382,6 +412,7 @@ def _variant_keys_from_filters(filters: Optional[dict]) -> set[str]:def _query_flag_evaluations(team: Team,user: User,+ shared_hogql: SharedHogQLDatabase,session_id: str,window_start: datetime,window_end: datetime,@@ -424,7 +455,9 @@ def _query_flag_evaluations("max_rows": ast.Constant(value=MAX_EXPOSURE_ROWS),},)- response = execute_hogql_query(query, team=team, user=user)+ response = execute_hogql_query(+ query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers+ )exposures: dict[str, list[tuple[str, datetime]]] = {}for flag_key, variant, first_seen in response.results or []:@@ -437,6 +470,7 @@ def _query_flag_evaluations(def _query_exposure_event_branches(team: Team,user: User,+ shared_hogql: SharedHogQLDatabase,session_id: str,window_start: datetime,window_end: datetime,@@ -504,7 +538,9 @@ def _query_exposure_event_branches(# No set-level LIMIT here: the printer emits it directly after the last branch's own# LIMIT, which ClickHouse rejects as a syntax error. The per-branch limits above are# the backstop; total output is already bounded by each flag's defined variants.- response = execute_hogql_query(query, team=team, user=user)+ response = execute_hogql_query(+ query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers+ )exposures: dict[int, list[tuple[str, datetime]]] = {}for experiment_id, variant, first_seen in response.results or []:@@ -517,6 +553,7 @@ def _query_exposure_event_branches(def _query_stamped_flag_properties(team: Team,user: User,+ shared_hogql: SharedHogQLDatabase,session_id: str,flag_keys: set[str],window_start: datetime,@@ -558,7 +595,9 @@ def _query_stamped_flag_properties(]),)- response = execute_hogql_query(query, team=team, user=user)+ response = execute_hogql_query(+ query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers+ )row = response.results[0] if response.results else [[] for _ in sorted_keys]return {key: [value for value in row[index] if value] for index, key in enumerate(sorted_keys)}diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 47366e78fc62..9a8fa74eb8eb 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -9,6 +9,9 @@ from django.core.cache import cachefrom rest_framework import status+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import Table, TableNode+from posthog.constants import AvailableFeaturefrom posthog.models import PropertyDefinition, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKey@@ -29,6 +32,14 @@ RECORDING_END = datetime(2026, 1, 1, 10, 30, 0, tzinfo=UTC)SESSION_ID = str(uuid7(unix_ms_time=int(RECORDING_START.timestamp() * 1000)))+def _hogql_table_tree(node: TableNode) -> dict[str, Any]:+ table = node.table+ return {+ "fields": sorted(table.fields) if isinstance(table, Table) else None,+ "children": {name: _hogql_table_tree(child) for name, child in node.children.items()},+ }++@freeze_time("2026-01-02T12:00:00Z")class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):def setUp(self) -> None:@@ -621,6 +632,46 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):compute.assert_not_called()assert second.json() == first.json()+ def test_uncached_request_shares_one_readonly_hogql_database(self) -> None:+ # Building the HogQL virtual database costs seconds on teams with a large warehouse+ # schema, so the endpoint builds one and shares it across every scan (exposures,+ # stamped properties, metric events) — concurrently, in production. Two regressions+ # pinned: a scan quietly building its own database (reintroduces the multi-second+ # latency), and a scan mutating the shared one (e.g. an information_schema-touching+ # query registers hidden external tables on it — a silent data race across the+ # production thread pool).+ self._create_recording()+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "33333333-3333-3333-3333-333333333333",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ self._create_experiment(metrics=[metric])+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ self._create_session_event(event="purchase", timestamp="2026-01-01T10:09:00Z")+ flush_persons_and_events()++ built: list[tuple[Database, dict[str, Any]]] = []+ original_create_for = Database.create_for++ def _capturing_create_for(*args: Any, **kwargs: Any) -> Database:+ database = original_create_for(*args, **kwargs)+ built.append((database, _hogql_table_tree(database.tables)))+ return database++ with patch.object(Database, "create_for", side_effect=_capturing_create_for) as create_for:+ response = self._get_session_context()++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert [result["flag_key"] for result in results] == ["checkout-cta"]+ assert results[0]["metrics_in_session"][0]["metric_uuid"] == metric["uuid"]+ assert create_for.call_count == 1+ database, tree_before_scans = built[0]+ assert _hogql_table_tree(database.tables) == tree_before_scans+def test_recording_not_found_is_not_cached(self) -> None:# A recording can 404 while still ingesting; that answer must not stick for the TTL.assert self._get_session_context().status_code == status.HTTP_404_NOT_FOUND