: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
fix(experiments): speed up replay session_context endpoint (#72838)
Marcel Poelkere13d3a274d4f
diff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.pyindex 442a6a999d17..573d7b6d0f2a 100644--- a/products/experiments/backend/metric_events.py+++ b/products/experiments/backend/metric_events.py@@ -11,6 +11,7 @@ endpoint."""import logging+from copy import deepcopyfrom dataclasses import dataclassfrom datetime import datetime@@ -28,7 +29,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.errors import BaseHogQLError-from posthog.hogql.parser import parse_selectfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query@@ -45,9 +45,10 @@ logger = logging.getLogger(__name__)# Per hit we return the first N event timestamps as seek points; event_count carries the true# total, so a busier metric shows the real count and the UI notes the seek points are capped.MAX_METRIC_EVENT_TIMESTAMPS = 50-# Ceiling on UNION ALL branches per scan. An experiment's metric count is user-configurable+# Ceiling on metrics accepted per scan. An experiment's metric count is user-configurable# with no server-side cap, so overlapping metric-heavy experiments could otherwise compile an-# arbitrarily wide union; 50 mirrors MAX_CANDIDATE_EXPERIMENTS in session_context.+# arbitrarily wide query or emit an unbounded hit list; 50 mirrors MAX_CANDIDATE_EXPERIMENTS+# in session_context.MAX_SCANNED_METRICS = 50MetricSourceNode = EventsNode | ActionsNode@@ -175,77 +176,136 @@ def scan_session_for_metric_events() -> list[MetricHit]:"""The metrics with >=1 matching event in the session, sorted by first occurrence.+ One scan computes every metric via conditional aggregation (countIf/minIf/groupArrayIf):+ a per-metric UNION ALL re-reads the session's event range once per metric, which dominated+ the endpoint's ClickHouse time in production once a session overlapped dozens of+ metric-carrying experiments. Keeping the OR of every metric condition in WHERE preserves+ the event-name primary-key pruning the per-metric branches had.+Metrics with no hits are omitted. Duplicate metric uuids (a saved metric shared by several- experiments) are scanned once, and at most MAX_SCANNED_METRICS metrics are scanned per call- (the overflow is logged, not an error). `user` threads through to HogQL for property-level- access control — metric source nodes can carry property filters.+ experiments) and metrics with identical source nodes (several experiments measuring the+ same event) are aggregated once, and at most MAX_SCANNED_METRICS metrics are accepted per+ call (the overflow is logged, not an error). The cap counts metrics, not distinct sources:+ source dedupe only narrows the query, it must not let a metric-heavy experiment emit an+ unbounded hit list by piling metrics onto one source. `user` threads through to HogQL for+ property-level access control — metric source nodes can carry property filters."""names_by_uuid: dict[str, str] = {}- branches: list[ast.SelectQuery] = []+ # Metric uuids grouped by identical source nodes: identical sources compile to identical+ # row conditions, so they share one aggregate set instead of re-counting the same events.+ uuids_by_source: dict[tuple[str, ...], list[str]] = {}+ conditions_by_source: dict[tuple[str, ...], ast.Expr] = {}skipped_over_cap = 0for source in metric_sources:if not source.session_linkable or source.metric_uuid in names_by_uuid:continue- if len(branches) >= MAX_SCANNED_METRICS:+ if len(names_by_uuid) >= MAX_SCANNED_METRICS:skipped_over_cap += 1continue+ source_key = tuple(sorted(node.model_dump_json(exclude_none=True) for node in source.nodes))+ if source_key in uuids_by_source:+ names_by_uuid[source.metric_uuid] = source.metric_name+ uuids_by_source[source_key].append(source.metric_uuid)+ continueconditions = [_node_condition(node, team) for node in source.nodes]if not conditions:continuenames_by_uuid[source.metric_uuid] = source.metric_name- branch = parse_select(- """- SELECT {metric_uuid} AS metric_uuid,- count() AS event_count,- min(timestamp) AS first_timestamp,- arraySlice(arraySort(groupArray(timestamp)), 1, {max_timestamps}) AS timestamps- FROM events- WHERE {metric_conditions}- AND $session_id = {session_id}- AND timestamp >= {window_start}- AND timestamp <= {window_end}- GROUP BY $session_id- """,- placeholders={- "metric_uuid": ast.Constant(value=source.metric_uuid),- "metric_conditions": ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0],- "session_id": ast.Constant(value=session_id),- "window_start": ast.Constant(value=window_start),- "window_end": ast.Constant(value=window_end),- "max_timestamps": ast.Constant(value=MAX_METRIC_EVENT_TIMESTAMPS),- },- )- assert isinstance(branch, ast.SelectQuery)- branches.append(branch)+ uuids_by_source[source_key] = [source.metric_uuid]+ conditions_by_source[source_key] = ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]if skipped_over_cap:logger.warning(- "Metric scan for session %s capped at %s branches; %s metrics not scanned",+ "Metric scan for session %s capped at %s metrics; %s metrics not scanned",session_id,MAX_SCANNED_METRICS,skipped_over_cap,)- if not branches:+ if not uuids_by_source:return []- # Each branch groups a single session, so it yields at most one row — the implicit- # LIMIT 100 HogQL stamps on every union branch can never truncate anything here.- query = ast.SelectSetQuery.create_from_queries(branches, "UNION ALL")+ # Condition asts are deep-copied per use site (three aggregates + the WHERE): the HogQL+ # resolver annotates nodes in place, so sharing one instance across positions is unsafe.+ source_keys = list(uuids_by_source)+ select: list[ast.Expr] = []+ for index, source_key in enumerate(source_keys):+ condition = conditions_by_source[source_key]+ select.append(ast.Alias(alias=f"count_{index}", expr=ast.Call(name="countIf", args=[deepcopy(condition)])))+ select.append(+ ast.Alias(+ alias=f"first_{index}",+ expr=ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), deepcopy(condition)]),+ )+ )+ select.append(+ ast.Alias(+ alias=f"timestamps_{index}",+ expr=ast.Call(+ name="arraySlice",+ args=[+ ast.Call(+ name="arraySort",+ args=[+ ast.Call(+ name="groupArrayIf",+ args=[ast.Field(chain=["timestamp"]), deepcopy(condition)],+ )+ ],+ ),+ ast.Constant(value=1),+ ast.Constant(value=MAX_METRIC_EVENT_TIMESTAMPS),+ ],+ ),+ )+ )++ any_metric_condition = [deepcopy(conditions_by_source[source_key]) for source_key in source_keys]+ query = ast.SelectQuery(+ select=select,+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["$session_id"]),+ right=ast.Constant(value=session_id),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=window_start),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=window_end),+ ),+ ast.Or(exprs=any_metric_condition) if len(any_metric_condition) > 1 else any_metric_condition[0],+ ]+ ),+ )response = execute_hogql_query(query, team=team, user=user)+ # 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.+ row = response.results[0] if response.results else None+ if row is None:+ return []hits: list[MetricHit] = []- for metric_uuid, event_count, first_timestamp, timestamps in response.results or []:+ for index, source_key in enumerate(source_keys):+ event_count, first_timestamp, timestamps = row[index * 3], row[index * 3 + 1], row[index * 3 + 2]if not event_count:continue- hits.append(- MetricHit(- metric_uuid=str(metric_uuid),- metric_name=names_by_uuid[str(metric_uuid)],- event_count=int(event_count),- first_timestamp=first_timestamp,- timestamps=tuple(timestamps),+ for metric_uuid in uuids_by_source[source_key]:+ hits.append(+ MetricHit(+ metric_uuid=metric_uuid,+ metric_name=names_by_uuid[metric_uuid],+ event_count=int(event_count),+ first_timestamp=first_timestamp,+ timestamps=tuple(timestamps),+ ))- )hits.sort(key=lambda hit: hit.first_timestamp)return hitsdiff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex 4641940d4ad7..da3472a9b6b0 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -20,10 +20,15 @@ what the session *saw*, not what the experiment analysis counts."""import logging+import contextvars+from concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom datetime import datetime, timedelta+from functools import partialfrom typing import Optional+from django.conf import settings+from django.core.cache import cachefrom django.db.models import Q, QuerySetimport pydantic@@ -38,6 +43,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.utils import get_safe_cachefrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.exposure_query_logic import (@@ -64,6 +70,11 @@ MAX_CANDIDATE_EXPERIMENTS = 50# is a backstop far above any real configuration — without it HogQL applies an implicit# LIMIT 100, which would silently and nondeterministically truncate legitimate rows.MAX_EXPOSURE_ROWS = 10_000+# Short-lived because the context is not immutable — late-arriving events, experiment edits,+# and access-control changes must all surface within minutes. The key includes the viewer:+# the experiment set is filtered by per-user access control, so entries must never be shared+# across users.+SESSION_CONTEXT_CACHE_TTL = 5 * 60@dataclass(frozen=True)@@ -105,7 +116,25 @@ def get_session_experiment_context(`user` is the viewer: exposure criteria can filter on arbitrary event/person properties,and the queries must enforce that user's property-level access control (as the experimentquery runners do) — userless execution would apply only the default property rules.++ Results are cached per (team, viewer, session) for SESSION_CONTEXT_CACHE_TTL so reopening+ a recording doesn't re-run the ClickHouse scans. "Recording not found" is not cached: the+ recording may simply still be ingesting."""+ cache_key = f"experiment_session_context_{team.pk}_{user.pk}_{session_id}"+ cached = get_safe_cache(cache_key)+ if cached is not None:+ return cached++ items = _compute_session_experiment_context(team, session_id, experiments, user)+ if items is not None:+ cache.set(cache_key, items, timeout=SESSION_CONTEXT_CACHE_TTL)+ return items+++def _compute_session_experiment_context(+ team: Team, session_id: str, experiments: QuerySet[Experiment], user: User+) -> Optional[list[ExperimentSessionContextItem]]:metadata = SessionReplayEvents().get_metadata(session_id, team)if metadata is None:return None@@ -169,37 +198,71 @@ def get_session_experiment_context(# 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.- flag_evaluations = _query_flag_evaluations(- team, user, session_id, window_start, window_end, set(flag_key_by_id.values()), all_variant_keys+ query_flag_evaluations = partial(+ _query_flag_evaluations,+ team,+ user,+ session_id,+ window_start,+ window_end,+ set(flag_key_by_id.values()),+ all_variant_keys,)- exposures: dict[int, list[tuple[str, datetime]]] = {- experiment_id: flag_evaluations[flag_key]- for experiment_id, flag_key in flag_key_by_id.items()- if experiment_id in batchable_ids and flag_key in flag_evaluations- }# Same width backstop as the candidate cap — each branch experiment adds a union branch, so# (unlike the constant-width flag-evaluations query) non-batchable experiments beyond the# cap are deliberately not queried: they get no criteria-driven exposure moment, though# flag evaluations still evidence (and rescue) them like any other experiment.- exposures.update(- _query_exposure_event_branches(- team, user, session_id, window_start, window_end, branch_meta[:MAX_CANDIDATE_EXPERIMENTS]- )+ query_exposure_branches = partial(+ _query_exposure_event_branches,+ team,+ user,+ session_id,+ window_start,+ window_end,+ branch_meta[:MAX_CANDIDATE_EXPERIMENTS],)+ 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+ )++ # The three scans are independent given the pre-rescue candidate set (only the rescue+ # follow-up below consumes another scan's output), so they run concurrently — total wait+ # is the slowest scan, not the sum. Sequential under TEST: worker threads open their own+ # DB connections, which can't see the test transaction's uncommitted data.+ if settings.TEST:+ flag_evaluations = query_flag_evaluations()+ branch_exposures = query_exposure_branches()+ stamped = query_stamped()+ else:+ with ThreadPoolExecutor(max_workers=3) as executor:+ # ThreadPoolExecutor does not inherit contextvars (query tags) by default; copy the+ # current context into each worker so tagged ClickHouse queries don't fail untagged.+ flag_evaluations_future = executor.submit(contextvars.copy_context().run, query_flag_evaluations)+ branch_exposures_future = executor.submit(contextvars.copy_context().run, query_exposure_branches)+ stamped_future = executor.submit(contextvars.copy_context().run, query_stamped)+ flag_evaluations = flag_evaluations_future.result()+ branch_exposures = branch_exposures_future.result()+ stamped = stamped_future.result()++ exposures: dict[int, list[tuple[str, datetime]]] = {+ experiment_id: flag_evaluations[flag_key]+ for experiment_id, flag_key in flag_key_by_id.items()+ if experiment_id in batchable_ids and flag_key in flag_evaluations+ }+ exposures.update(branch_exposures)# The exposure queries cover every overlapping experiment's flag (not just the capped# candidates), so a flag with verifiable in-session evidence rescues its experiment even- # when it fell outside the cap above. Rescued keys join the stamped-property query too —- # it stays bounded, since rescues are limited to real overlapping experiments the session- # demonstrably called.+ # when it fell outside the cap above. Rescued keys join the stamped-property evidence too,+ # through a follow-up query for just those keys (the main stamped scan already ran on the+ # pre-rescue candidates) — it stays bounded, since rescues are limited to real overlapping+ # experiments the session demonstrably called.evidenced_keys = set(flag_evaluations) | {flag_key_by_id[experiment_id] for experiment_id in exposures}- candidate_keys = {experiment.feature_flag.key for experiment in candidates}rescued_keys = evidenced_keys - candidate_keysif rescued_keys:candidates += list(overlapping.filter(feature_flag__key__in=sorted(rescued_keys)))- candidate_keys = {experiment.feature_flag.key for experiment in candidates}-- stamped = _query_stamped_flag_properties(team, user, session_id, candidate_keys, window_start, window_end)+ stamped.update(_query_stamped_flag_properties(team, user, session_id, rescued_keys, window_start, window_end))surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]] = []for experiment in candidates:diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.pyindex f3c1dffce80e..b672d69add09 100644--- a/products/experiments/backend/test/test_metric_events.py+++ b/products/experiments/backend/test/test_metric_events.py@@ -233,9 +233,9 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin))def test_reports_hits_only_for_metrics_with_in_window_events(self) -> None:- # Two metrics force a genuine multi-branch UNION ALL — a single branch collapses to a- # plain SelectQuery, so only this shape proves the union compiles and that a metric- # with no matching events yields no hit.+ # Two metrics with different sources prove the combined query aggregates each source+ # separately and that a metric with no matching events yields no hit (its aggregate+ # row shows count 0, which must not surface as a hit with an epoch timestamp).metric_a = _metric("mean", name="Purchases", source=_events_node("purchase"))metric_b = _metric("mean", name="Signups", source=_events_node("signup"))self._create_session_event("purchase", "s1", timestamp="2026-01-01T10:05:00Z")@@ -309,16 +309,34 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)assert [hit.metric_uuid for hit in hits] == [purchases["uuid"]]+ def test_metrics_with_identical_sources_each_report_their_hit(self) -> None:+ # Overlapping experiments routinely measure the same event (production sessions show+ # identical sources under different metric uuids); those sources share one aggregate+ # set in the scan, and every metric uuid must still get its own hit back.+ first = _metric("mean", name="Purchases", source=_events_node("purchase"))+ second = _metric("mean", name="Purchases too", source=_events_node("purchase"))+ self._create_session_event("purchase", "s1")+ flush_persons_and_events()++ hits = self._scan([first, second], "s1")++ assert sorted(hit.metric_uuid for hit in hits) == sorted([first["uuid"], second["uuid"]])+ assert all(hit.event_count == 1 for hit in hits)+def test_scan_caps_number_of_scanned_metrics(self) -> None:- # Metric counts are user-configurable with no server-side cap; without the branch cap a- # metric-heavy experiment would compile an arbitrarily wide UNION ALL per player open.+ # Metric counts are user-configurable with no server-side cap; without the metric cap a+ # metric-heavy experiment would compile an arbitrarily wide scan per player open. The+ # cap must count metrics, not distinct sources: a metric sharing an already-accepted+ # source (`shared`) adds no query width, but letting it through would let many metrics+ # on one source emit an unbounded hit list.first = _metric("mean", name="Purchases", source=_events_node("purchase"))second = _metric("mean", name="Signups", source=_events_node("signup"))+ shared = _metric("mean", name="Purchases too", source=_events_node("purchase"))self._create_session_event("purchase", "s1")self._create_session_event("signup", "s1")flush_persons_and_events()with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):- hits = self._scan([first, second], "s1")+ hits = self._scan([first, second, shared], "s1")assert [hit.metric_uuid for hit in hits] == [first["uuid"]]diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 21964bb06027..47366e78fc62 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -5,6 +5,8 @@ from freezegun import freeze_timefrom posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patch+from django.core.cache import cache+from rest_framework import statusfrom posthog.constants import AvailableFeature@@ -29,6 +31,12 @@ SESSION_ID = str(uuid7(unix_ms_time=int(RECORDING_START.timestamp() * 1000)))@freeze_time("2026-01-02T12:00:00Z")class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):+ def setUp(self) -> None:+ super().setUp()+ # Every test shares SESSION_ID and the local-memory cache outlives a test; the context+ # cache key includes the per-test team, but clear anyway so no test can see another's entry.+ cache.clear()+def _create_recording(self, session_id: str = SESSION_ID, team_id: Optional[int] = None) -> None:produce_replay_summary(team_id=team_id if team_id is not None else self.team.pk,@@ -570,6 +578,62 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert response.status_code == status.HTTP_200_OKassert [result["flag_key"] for result in response.json()["results"]] == ["checkout-cta"]+ def test_cached_context_is_not_shared_across_users(self) -> None:+ self._enable_access_controls()+ other_user = self._create_user("[email protected]")+ self._create_recording()+ self._create_experiment()+ private_experiment = self._create_experiment(+ key="private-exp", name="Private experiment", created_by=other_user+ )+ AccessControl.objects.create(+ team=self.team, resource="experiment", resource_id=str(private_experiment.pk), access_level="none"+ )+ self._create_session_event(+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ self._create_session_event(+ properties={"$feature_flag": "private-exp", "$feature_flag_response": "control"},+ )+ flush_persons_and_events()++ # Prime the cache as the private experiment's creator, who sees both experiments.+ self.client.force_login(other_user)+ response = self._get_session_context()+ assert [result["flag_key"] for result in response.json()["results"]] == ["checkout-cta", "private-exp"]++ # The cached entry must not leak the private experiment to a viewer without access.+ self.client.force_login(self.user)+ response = self._get_session_context()+ assert [result["flag_key"] for result in response.json()["results"]] == ["checkout-cta"]++ def test_repeat_request_is_served_from_cache(self) -> None:+ self._create_recording()+ self._create_experiment()+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ flush_persons_and_events()++ first = self._get_session_context()+ assert first.status_code == status.HTTP_200_OK++ with patch("products.experiments.backend.session_context._compute_session_experiment_context") as compute:+ second = self._get_session_context()+ compute.assert_not_called()+ assert second.json() == first.json()++ 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++ self._create_recording()+ self._create_experiment()+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ assert [result["flag_key"] for result in response.json()["results"]] == ["checkout-cta"]+def test_403_without_session_recording_resource_access(self) -> None:self._enable_access_controls()AccessControl.objects.create(team=self.team, resource="session_recording", access_level="none")@@ -605,9 +669,9 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):def test_metrics_in_session(self) -> None:self._create_recording()- # Two overlapping experiments with a metric each force a genuine multi-branch UNION ALL- # in the metric scan — a single branch collapses to a plain SelectQuery, so only this- # shape proves the union compiles end to end through the endpoint.+ # Two overlapping experiments with a metric each force a multi-metric aggregate set in+ # the metric scan, proving the combined single-pass query compiles end to end through+ # the endpoint — and that a metric with no matching events stays inert.metric = {"kind": "ExperimentMetric","metric_type": "mean",