Skip to content

: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.

fix(experiments): unblock the recordings tab for activation exposures (#83514)

Marcel Poelker7d1ff4dae07d
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index 673c2e7ff7cd..42a561082674 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -227,6 +227,18 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._resolve_experiment_exposure()
query = self.get_query()
+ settings_args: dict[str, int] = {}
+ if self._max_execution_time is not None:
+ settings_args["max_execution_time"] = self._max_execution_time
+ linkage = self._experiment_exposure_linkage
+ if linkage is not None and linkage.live_scan_max_memory_bytes is not None:
+ # Deliberately no exposure-specific rendering of the resulting memory kill: the
+ # ceiling bounds the whole listing query (event filters, blocklist, aggregation),
+ # not just the exposure scan, so only the platform's standard memory-limit error,
+ # with its status, machine code, and narrow-your-filters guidance, is honest for
+ # every cause.
+ settings_args["max_memory_usage"] = linkage.live_scan_max_memory_bytes
+
with tracer.start_as_current_span("SessionRecordingListFromQuery.paginate"):
paginated_response = self._paginator.execute_hogql_query(
# TODO I guess the paginator needs to know how to handle union queries or all callers are supposed to collapse them or .... 🤷
@@ -235,11 +247,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
user=self._user,
query_type="SessionRecordingListQuery",
modifiers=self._hogql_query_modifiers,
- settings=HogQLGlobalSettings(
- **(
- {"max_execution_time": self._max_execution_time} if self._max_execution_time is not None else {}
- ),
- ),
+ settings=HogQLGlobalSettings(**settings_args),
)
# After the results are in, check whether the exclusion blocklist hit its row cap,
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
index 9458a3fd95ec..c7468198e476 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
@@ -1,5 +1,6 @@
import json
from datetime import UTC, datetime, timedelta
+from typing import cast
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
@@ -10,8 +11,12 @@ from rest_framework.exceptions import PermissionDenied, ValidationError
from posthog.schema import RecordingsQuery
+from posthog.hogql.constants import HogQLGlobalSettings
+
from posthog.clickhouse.client import sync_execute
from posthog.constants import AvailableFeature
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.hogql_queries.insights.paginators import HogQLCursorPaginator
from posthog.models import User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.extensions import get_or_create_team_extension
@@ -31,6 +36,12 @@ from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SES
from posthog.test.persons import add_distinct_id, create_person
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
+from products.cohorts.backend.models.cohort import Cohort
+
+# Importing the facade at module scope also keeps its transitive pydantic.v1 import outside the
+# class's frozen time: freezegun's FakeDate breaks pydantic.v1's metaclass construction, and the
+# runner otherwise defers this import to the first test that resolves a linkage.
+from products.experiments.backend.facade.replay import ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES
from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -532,7 +543,11 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase
)
self.assertIn("still being computed", str(error_context.exception.detail))
- def test_rejects_activation_mode_on_precomputing_teams(self) -> None:
+ def test_activation_mode_scans_live_even_on_precomputing_teams(self) -> None:
+ # Activation exposures have no preaggregated form, so on precomputing teams they must
+ # scan live rather than refuse, and must not reach ensure_precomputed: a cache built
+ # from the flag predicate alone would ignore the activation ordering and include the
+ # session between flag exposure and activation.
self._enable_precomputation()
experiment = self._create_experiment(
exposure_criteria={
@@ -543,6 +558,54 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase
}
}
)
+ create_person(team=self.team, distinct_ids=["activated-user"])
+ flag_exposure_time = BASE_TIME + timedelta(minutes=30)
+ activation_time = BASE_TIME + timedelta(hours=3)
+ self._create_exposure_event("activated-user", flag_exposure_time, "test")
+ _create_event(
+ team=self.team,
+ event="task_completed",
+ distinct_id="activated-user",
+ timestamp=activation_time,
+ properties={},
+ )
+ flush_persons_and_events()
+
+ self._produce_recording(
+ "activated-user",
+ "session-before-activation",
+ flag_exposure_time + timedelta(minutes=30),
+ flag_exposure_time + timedelta(minutes=45),
+ )
+ self._produce_recording(
+ "activated-user",
+ "session-after-activation",
+ activation_time + timedelta(minutes=30),
+ activation_time + timedelta(minutes=45),
+ )
+
+ with patch("products.experiments.backend.replay_linkage.ensure_precomputed") as ensure_mock:
+ self._assert_query_matches_session_ids(
+ {"experiment_exposure": {"experiment_id": experiment.id}},
+ ["session-after-activation"],
+ )
+ ensure_mock.assert_not_called()
+
+ def test_activation_mode_with_uncalculated_cohort_asks_to_retry(self) -> None:
+ # An uncalculated cohort's membership rows are only partially inserted, so a live
+ # activation scan filtered by it would silently undercount the exposed population;
+ # the linkage must refuse with the retryable cohort error instead.
+ self._enable_precomputation()
+ cohort = Cohort.objects.create(team=self.team, name="mid first calculation", is_static=False)
+ experiment = self._create_experiment(
+ exposure_criteria={
+ "activation_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "task_completed",
+ "properties": [{"key": "id", "type": "cohort", "value": cohort.pk}],
+ }
+ }
+ )
with self.assertRaises(ValidationError) as error_context:
filter_recordings_by(
@@ -550,7 +613,39 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase
recordings_filter={"experiment_exposure": {"experiment_id": experiment.id}},
user=self.user,
)
- self.assertIn("activation event", str(error_context.exception.detail))
+ self.assertIn("hasn't finished calculating", str(error_context.exception.detail))
+
+ def test_activation_live_scan_is_memory_bounded_and_memory_kills_keep_their_rendering(self) -> None:
+ # Precomputing teams get no unbounded live path: the listing query must carry the
+ # activation memory ceiling. A kill under it must propagate as the platform's
+ # standard memory-limit error, never an exposure-specific translation: the ceiling
+ # bounds the whole listing query, so the runner can't attribute a kill to the
+ # exposure scan.
+ self._enable_precomputation()
+ experiment = self._create_experiment(
+ exposure_criteria={
+ "activation_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "task_completed",
+ "properties": [],
+ }
+ }
+ )
+
+ executed_settings: list[HogQLGlobalSettings] = []
+
+ def record_settings_and_hit_the_ceiling(*args: object, **kwargs: object) -> None:
+ executed_settings.append(cast(HogQLGlobalSettings, kwargs["settings"]))
+ raise ClickHouseQueryMemoryLimitExceeded()
+
+ with patch.object(HogQLCursorPaginator, "execute_hogql_query", side_effect=record_settings_and_hit_the_ceiling):
+ with self.assertRaises(ClickHouseQueryMemoryLimitExceeded):
+ filter_recordings_by(
+ team=self.team,
+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id}},
+ user=self.user,
+ )
+ self.assertEqual(executed_settings[0].max_memory_usage, ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES)
def test_young_experiments_scan_live_even_on_precomputing_teams(self) -> None:
# Started 6 hours before the frozen now, under the 12-hour precompute minimum. The
diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.py
index a292616e2d4b..fe33b614fc88 100644
--- a/products/experiments/backend/facade/replay.py
+++ b/products/experiments/backend/facade/replay.py
@@ -1,6 +1,7 @@
"""Replay linkage capability, re-exported for callers outside the experiments product."""
from products.experiments.backend.replay_linkage import (
+ ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,
ExperimentExposureLinkage,
exposed_distinct_ids_select,
resolve_exposure_linkage,
@@ -8,6 +9,7 @@ from products.experiments.backend.replay_linkage import (
)
__all__ = [
+ "ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES",
"ExperimentExposureLinkage",
"exposed_distinct_ids_select",
"resolve_exposure_linkage",
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index e00dce1a9353..05675b29fa44 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -23,8 +23,10 @@ The work splits in two, because recordings queries build their AST separately fr
The exposure scan window is deliberately the full experiment window, unbounded. Narrowing it
would change who counts as exposed relative to the analysis. The expensive cases are handled
instead: precomputing teams read the preaggregated table (converging in TTL-capped chunks for
-long-running experiments), and where neither the preaggregated read nor an affordable live
-scan is available the query is refused with a ValidationError rather than left to time out.
+long-running experiments), activation-mode exposures always resolve with a live scan because
+they have no preaggregated form (carrying an explicit memory budget on precomputing teams),
+and where neither the preaggregated read nor an affordable live scan is available the query
+is refused with a ValidationError rather than left to time out.
"""
from dataclasses import dataclass
@@ -71,14 +73,15 @@ logger = structlog.get_logger(__name__)
EXPOSURES_STILL_COMPUTING_MESSAGE = (
"Exposed users for this experiment are still being computed. Try again in a few minutes."
)
-ACTIVATION_NOT_PRECOMPUTABLE_MESSAGE = (
- "This experiment counts exposure from an activation event, which can't be precomputed, "
- "and this project is too large to resolve its exposed users live."
-)
COHORT_NOT_CALCULATED_MESSAGE = (
"This experiment's exposure criteria reference a cohort that hasn't finished calculating. "
"Try again when the cohort is ready."
)
+# Sized an order of magnitude above the peak observed on the largest precompute-enabled team
+# (#83514), so it fires only for a scan far outside anything measured, and below the cluster's
+# default per-query limit, so the kill renders as the standard memory-limit error before the
+# scan becomes cluster-level pressure.
+ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES = 4 * 1024**3
def validate_experiment_exposure_access(
@@ -127,6 +130,13 @@ class ExperimentExposureLinkage:
requested_variants: list[str]
# Set = read the preaggregated exposures written by these jobs. None = live events scan.
preaggregation_job_ids: list[str] | None
+ # max_memory_usage ceiling the synchronous recordings-list run must apply when the live
+ # scan needs explicit bounding instead of relying on cluster defaults. It bounds the whole
+ # embedding query, so a kill renders as the platform's generic memory-limit error rather
+ # than anything exposure-specific. Composition callers that execute the linkage's AST
+ # through their own async or batch pipelines run under those pipelines' limits and may
+ # ignore it.
+ live_scan_max_memory_bytes: int | None = None
def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | None) -> ExperimentExposureLinkage:
@@ -192,25 +202,35 @@ def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | N
cuped_config=CupedQueryConfig(),
activation_config=exposure_params.activation_config,
)
+ read = _resolve_exposure_read(team, experiment, context)
return ExperimentExposureLinkage(
context=context,
requested_variants=requested_variants,
- preaggregation_job_ids=_resolve_preaggregation_job_ids(team, experiment, context),
+ preaggregation_job_ids=read.preaggregation_job_ids,
+ live_scan_max_memory_bytes=read.live_scan_max_memory_bytes,
)
-def _resolve_preaggregation_job_ids(
- team: Team, experiment: Experiment, context: ExperimentQueryContext
-) -> list[str] | None:
- """Preaggregation job ids covering the experiment window, or None for a live scan.
+@dataclass(frozen=True, kw_only=True)
+class _ExposureRead:
+ preaggregation_job_ids: list[str] | None
+ live_scan_max_memory_bytes: int | None
+
+
+def _resolve_exposure_read(team: Team, experiment: Experiment, context: ExperimentQueryContext) -> _ExposureRead:
+ """How the exposed population will be read: preaggregation job ids, or a live scan.
The eligibility gates mirror the exposures-chart runner's, but the fallback posture
inverts: the analysis can always fall back to a direct scan, because it runs through
- the async query pipeline with generous limits. This linkage runs inside a synchronous
- recordings-list GET, where the production assessment showed the live scan cannot
- complete on the largest teams. Precomputation being enabled is the team-level marker
- for exactly those teams, so on them an unavailable preaggregated read is refused
- instead of silently attempting the scan that precomputation exists to avoid.
+ the async query pipeline with generous limits, while this linkage runs inside a
+ synchronous recordings-list GET. Precomputation being enabled is the team-level
+ marker for the teams where the full-window live scan is a real cost, so on them a
+ transiently unavailable preaggregated read (still computing, cohort mid-calculation)
+ is refused instead of silently attempting the scan that precomputation exists to
+ avoid. Activation mode is the exception: it has no preaggregated form at all, and
+ its live scan stays affordable because its memory is bounded by the exposed
+ population, so it scans live under an explicit memory budget rather than being
+ permanently refused.
"""
config = get_or_create_team_extension(team, TeamExperimentsConfig)
# Below the minimum runtime the analysis skips precomputation too: the scan window is
@@ -220,18 +240,28 @@ def _resolve_preaggregation_job_ids(
experiment.start_date, experiment.end_date
):
tag_queries(experiment_exposures_path="direct_scan")
- return None
+ return _ExposureRead(preaggregation_job_ids=None, live_scan_max_memory_bytes=None)
- if has_activation_config(experiment.exposure_criteria):
- # The flag-to-activation ordering crosses the per-day cache buckets, so activation
- # exposures can't be precomputed. A per-experiment live path for them is deliberately
- # not built: activation mode is a negligible slice of running experiments.
- raise ValidationError(ACTIVATION_NOT_PRECOMPUTABLE_MESSAGE)
if has_uncalculated_cohorts(team, experiment.exposure_criteria):
- # A build during the cohort's first materialization would freeze a torn membership
- # snapshot for the frozen-band TTL; transient, so the error says to retry.
+ # Both reads below see the cohort's partially-inserted membership: a precompute build
+ # would freeze the torn snapshot for the frozen-band TTL, and the activation live scan
+ # would silently undercount. Transient, so the error says to retry.
raise ValidationError(COHORT_NOT_CALCULATED_MESSAGE)
+ if has_activation_config(experiment.exposure_criteria):
+ # The flag-to-activation ordering crosses the per-day cache buckets, so activation
+ # exposures have no preaggregated form. Their live scan stays affordable even on the
+ # largest teams, because it is bounded by the experiment window's activation events
+ # and the distinct-id expansion's memory scales with the exposed population, so they
+ # scan live instead of being refused. The ceiling keeps the scan explicitly bounded:
+ # one that outgrows it is killed with the standard memory-limit error instead of
+ # pressuring the cluster.
+ tag_queries(experiment_exposures_path="direct_scan_activation")
+ return _ExposureRead(
+ preaggregation_job_ids=None,
+ live_scan_max_memory_bytes=ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,
+ )
+
query_string, placeholders = ExposureQueryBuilder(context=context).precomputation_query()
assert experiment.start_date is not None
try:
@@ -257,7 +287,10 @@ def _resolve_preaggregation_job_ids(
raise ValidationError(EXPOSURES_STILL_COMPUTING_MESSAGE)
tag_queries(experiment_exposures_path="precomputed")
- return [str(job_id) for job_id in result.job_ids]
+ return _ExposureRead(
+ preaggregation_job_ids=[str(job_id) for job_id in result.job_ids],
+ live_scan_max_memory_bytes=None,
+ )
def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.SelectQuery: