: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): improve decision for replay-session cache-writes to work for experiment-heavy teams (#74721)
Marcel Poelker7cb2bbb2a50e
diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex 437d6c80d8d0..8dd8d3bc50b4 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -48,6 +48,10 @@ from posthog.session_recordings.queries.session_replay_events import SessionReplfrom posthog.utils import get_safe_cachefrom products.cohorts.backend.models.cohort import Cohort++# The module is also imported whole: the capped-session check reads MAX_SCANNED_METRICS as a+# module attribute so it always sees the same value the scan applies (tests patch it there).+from products.experiments.backend import metric_eventsfrom products.experiments.backend.hogql_queries.exposure_query_logic import (build_exposure_event_conditions,get_exposure_event_and_property,@@ -209,9 +213,12 @@ def get_session_experiment_contexts(metadata doesn't exist (yet) are omitted and never cached, mirroring the single endpoint'snot-found rule; so are ids without a parseable uuidv7 timestamp, whose metadata lookupwould otherwise run unbounded. The batch is best-effort: a day-chunk whose scans fail is- logged and omitted rather than failing the whole request, and a session whose metric enrichment was- truncated by the shared scan's metric cap is returned but not cached, so the cache never- holds less than a single-session request would compute.+ logged and omitted rather than failing the whole request, and a session is returned but+ not cached when the shared scan's metric cap dropped a metric that session's own+ single-session scan would have kept — so the cache never holds less than a single-session+ request would compute. A session whose own metrics already exceed the cap is cached+ despite the truncation: a recompute would drop the same metrics again, mirroring how the+ single-session endpoint caches its own capped results."""unique_ids = list(dict.fromkeys(session_ids))results: dict[str, list[ExperimentSessionContextItem]] = {}@@ -250,9 +257,10 @@ def get_session_experiment_contexts(team, windows, experiments, user, fail_open=True)for session_id, items in computed.items():- # A session whose metric enrichment was truncated by the batch-wide scan cap is- # returned best-effort but never cached: the single-session endpoint scans only that- # session's own experiments, so its recompute restores the full set the batch dropped.+ # A capped session lost a metric to the batch-wide scan cap that its own+ # single-session scan would have kept, so caching would serve less than the+ # single-session endpoint computes; it is returned best-effort and left for+ # on-demand recompute instead.if session_id not in capped_session_ids:cache.set(_cache_key(team, user, session_id), items, timeout=SESSION_CONTEXT_CACHE_TTL)results.update(computed)@@ -293,9 +301,11 @@ def _compute_session_experiment_contexts(*,fail_open: bool,) -> tuple[dict[str, list[ExperimentSessionContextItem]], set[str]]:- """Returns (session_id -> items, capped session ids). Capped sessions had metric enrichment- truncated by the batch-wide scan cap; their items are still returned, but the batch caller- must not cache them, because a single-session recompute would return more."""+ """Returns (session_id -> items, capped session ids). Capped sessions had a metric dropped+ by the batch-wide scan cap that their own single-session scan would have kept; their items+ are still returned, but the batch caller must not cache them, because a single-session+ recompute would return more. Sessions whose own metrics exceed the cap by themselves are+ not marked capped — a recompute would drop the same metrics — so they stay cacheable."""if not windows:return {}, set()@@ -585,19 +595,23 @@ def _compute_chunk_contexts(surfaced.append((experiment, variant, variants_seen, first_exposure_timestamp))surfaced_by_session[session_id] = surfaced- # Only the experiments that actually surfaced (typically 1–3 per session, not the candidate- # cap) get their metrics scanned — one scan covers the union across the chunk's sessions,- # shared saved metrics dedupe by uuid inside the scan, and each session's experiments claim- # their own metrics' hits back by uuid. MAX_SCANNED_METRICS caps that union in surfacing- # order, so a batch can drop metrics of a co-occurring experiment that a single request for- # the same session (whose own surfaced experiments rarely approach the cap) would return.- # On the experiment tab every session surfaces the target experiment, which therefore- # registers within the first session's block and in practice survives; the sessions whose- # experiments lost metrics are reported as capped below so the batch never caches them —- # any caller wanting their full set recomputes per session on demand. Metric hits are- # enrichment on top of the exposure context: an unexpected failure here (one experiment's- # malformed stored metric, say) must degrade to "no metric hits", never take down the- # exposure context that already resolved above.+ # Only the experiments that actually surfaced get their metrics scanned — one scan covers+ # the union across the chunk's sessions, shared saved metrics dedupe by uuid inside the+ # scan, and each session's experiments claim their own metrics' hits back by uuid.+ # MAX_SCANNED_METRICS caps that union in surfacing order. On experiment-heavy teams a+ # single session can surface dozens of experiments carrying well over the cap by itself,+ # so hitting the cap is the steady state there, for the batch and single request alike.+ # A session is reported as capped below only when the batch dropped a metric its own+ # single-session scan would have kept (see _single_scan_accepted_uuids) — those the batch+ # never caches, so a single request can recompute the fuller set on demand. Sessions whose+ # own metrics exceed the cap anyway stay cacheable: a recompute would drop the same+ # metrics, so withholding the cache entry would buy nothing and cost a full recompute per+ # open (which, before this distinction, made the prefetch useless on experiment-heavy+ # teams — every session shares the same over-cap experiment set, so every session was+ # marked capped and nothing was ever cached). Metric hits are enrichment on top of the+ # exposure context: an unexpected failure here (one experiment's malformed stored metric,+ # say) must degrade to "no metric hits", never take down the exposure context that already+ # resolved above.sources_by_experiment: dict[int, list[MetricEventSource]] = {}hits_by_session: dict[str, dict[str, MetricHit]] = {}dropped_metric_uuids: set[str] = set()@@ -632,11 +646,7 @@ def _compute_chunk_contexts(capped_session_ids = {session_idfor session_id, session_surfaced in surfaced_by_session.items()- if any(- source.metric_uuid in dropped_metric_uuids- for experiment, *_ in session_surfaced- for source in sources_by_experiment.get(experiment.pk, [])- )+ if dropped_metric_uuids & _single_scan_accepted_uuids(session_surfaced, sources_by_experiment)}results: dict[str, list[ExperimentSessionContextItem]] = {}@@ -670,6 +680,29 @@ def _compute_chunk_contexts(return results, capped_session_ids+def _single_scan_accepted_uuids(+ session_surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]],+ sources_by_experiment: dict[int, list[MetricEventSource]],+) -> set[str]:+ """The metric uuids a single-session request's scan would accept for this session.++ Mirrors scan_sessions_for_metric_events' acceptance rule — the first MAX_SCANNED_METRICS+ distinct session-linkable uuids, in source order — applied to only this session's surfaced+ experiments. The order matches what a single-session request produces: its scan receives+ the session's surfaced experiments in candidate (newest-first) order, which is exactly the+ order of `session_surfaced` here. A batch-dropped uuid outside this set would be dropped+ by a single-session recompute too, so it must not disqualify the session from caching."""+ accepted: set[str] = set()+ for experiment, *_ in session_surfaced:+ for source in sources_by_experiment.get(experiment.pk, []):+ if not source.session_linkable or source.metric_uuid in accepted:+ continue+ if len(accepted) >= metric_events.MAX_SCANNED_METRICS:+ return accepted+ accepted.add(source.metric_uuid)+ return accepted++def _resolve_exposure(flag_key: str, exposure_criteria: Optional[dict]) -> _ResolvedExposure:"""Resolve an experiment's exposure criteria through the shared `exposure_query_logic`helpers — the single seam that keeps this surface in sync with the experiment analysis.diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 86c759b94ed1..49efb4e49250 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -19,6 +19,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.rate_limit import SessionContextsBurstRateThrottlefrom posthog.session_recordings.models.session_recording import SessionRecording+from posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.access_control.backend.facade.api import upsert_property_access_control@@ -1040,38 +1041,38 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):by_id = {entry["session_id"]: entry["results"] for entry in response.json()["results"]}assert [result["variant"] for result in by_id[DAY_TWO_SESSION_ID]] == ["control"]- def test_batch_never_caches_sessions_whose_metrics_were_capped(self) -> None:- # The chunk-wide scan caps the metric union across a batch's sessions, so it can drop a- # co-occurring experiment's metrics for a session whose own single request (scanning- # only that session's experiments) would return them. Caching that truncated result- # would serve it as truth for the TTL; the capped session must be returned best-effort- # but left uncached, while unaffected sessions stay cacheable.- shared_metric = {+ def test_batch_never_caches_sessions_a_single_request_would_enrich_more(self) -> None:+ # The chunk-wide scan caps the metric union across a batch's sessions, so a session+ # registered later can lose a metric its own single-session scan (same cap, but only+ # its own experiments) would have kept. Caching that truncated result would serve it as+ # truth for the TTL; the session must be returned best-effort but left uncached, while+ # the session that claimed the budget stays cacheable.+ first_metric = {"kind": "ExperimentMetric","metric_type": "mean","uuid": "22222222-2222-2222-2222-222222222222","name": "Purchases","source": {"kind": "EventsNode", "event": "purchase"},}- extra_metric = {+ second_metric = {"kind": "ExperimentMetric","metric_type": "mean","uuid": "33333333-3333-3333-3333-333333333333","name": "Signups","source": {"kind": "EventsNode", "event": "signup"},}- # The shared experiment is newer, and candidates iterate newest-first, so its metric- # takes the only patched slot whichever session the scan registers first.self._create_experiment(- key="shared-exp",- name="Shared experiment",+ key="first-exp",+ name="First experiment",start_date=datetime(2025, 12, 15, tzinfo=UTC),- metrics=[shared_metric],+ metrics=[first_metric],)- self._create_experiment(key="extra-exp", name="Extra experiment", metrics=[extra_metric])+ self._create_experiment(key="second-exp", name="Second experiment", metrics=[second_metric])+ # Each session surfaces a different experiment, so which metric survives the patched+ # one-slot cap is decided purely by session registration order — pinned below.self._create_recording()- self._create_session_event(properties={"$feature_flag": "shared-exp", "$feature_flag_response": "test"})+ self._create_session_event(properties={"$feature_flag": "first-exp", "$feature_flag_response": "test"})self._create_session_event(event="purchase", timestamp="2026-01-01T10:09:00Z")# A second same-day recording, so both sessions share one chunk (and one metric scan).@@ -1087,12 +1088,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):("$feature_flag_called","2026-01-01T10:41:00Z",- {"$feature_flag": "shared-exp", "$feature_flag_response": "test"},- ),- (- "$feature_flag_called",- "2026-01-01T10:42:00Z",- {"$feature_flag": "extra-exp", "$feature_flag_response": "control"},+ {"$feature_flag": "second-exp", "$feature_flag_response": "control"},),("signup", "2026-01-01T10:43:00Z", {}),):@@ -1101,29 +1097,99 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):)flush_persons_and_events()- with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):+ # Sessions register their metrics in window order, and windows follow the metadata+ # lookup's dict order — which follows ClickHouse row order. Pin it so the first+ # session's metric deterministically takes the only patched slot.+ original_get_group_metadata = SessionReplayEvents.get_group_metadata++ def _ordered_metadata(+ replay_events: SessionReplayEvents, session_ids: list[str], team: Team, **kwargs: Any+ ) -> dict[str, Any]:+ metadata = original_get_group_metadata(replay_events, session_ids, team, **kwargs)+ return {session_id: metadata[session_id] for session_id in (SESSION_ID, second_session_id)}++ with (+ patch.object(SessionReplayEvents, "get_group_metadata", _ordered_metadata),+ patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1),+ ):response = self._post_session_contexts([SESSION_ID, second_session_id])assert response.status_code == status.HTTP_200_OKby_id = {entry["session_id"]: entry["results"] for entry in response.json()["results"]}- assert [hit["metric_uuid"] for hit in by_id[SESSION_ID][0]["metrics_in_session"]] == [shared_metric["uuid"]]- second_by_flag = {result["flag_key"]: result for result in by_id[second_session_id]}- assert second_by_flag["extra-exp"]["metrics_in_session"] == []+ assert [hit["metric_uuid"] for hit in by_id[SESSION_ID][0]["metrics_in_session"]] == [first_metric["uuid"]]+ assert by_id[second_session_id][0]["metrics_in_session"] == []- # The unaffected session was cached: the single endpoint serves it without recomputing.+ # The session that kept its metric was cached: the single endpoint serves it without+ # recomputing.with patch("products.experiments.backend.session_context._compute_session_experiment_contexts") as compute:single_first = self._get_session_context()compute.assert_not_called()assert single_first.json()["results"] == by_id[SESSION_ID]- # The capped session was not cached: the single endpoint recomputes it with only its- # own experiments' metrics (under the real cap) and restores the dropped hit.- single_second = self._get_session_context(second_session_id)- second_results = {result["flag_key"]: result for result in single_second.json()["results"]}- assert [hit["metric_uuid"] for hit in second_results["extra-exp"]["metrics_in_session"]] == [- extra_metric["uuid"]+ # The capped session was not cached: under the same cap, the single endpoint's scan+ # covers only this session's experiment, so the recompute restores the dropped hit.+ with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):+ single_second = self._get_session_context(second_session_id)+ assert [hit["metric_uuid"] for hit in single_second.json()["results"][0]["metrics_in_session"]] == [+ second_metric["uuid"]]+ def test_batch_caches_capped_session_a_single_request_could_not_improve(self) -> None:+ # On experiment-heavy teams a single session's own surfaced experiments carry more+ # metrics than the scan cap, so every batch (and every single request) is capped in+ # steady state. Metrics the session's own scan would drop anyway must not disqualify+ # it from caching — otherwise the batch prefetch never caches anything on exactly the+ # teams that need it most, and every open recomputes the same truncated result.+ first_metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "22222222-2222-2222-2222-222222222222",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ second_metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "33333333-3333-3333-3333-333333333333",+ "name": "Signups",+ "source": {"kind": "EventsNode", "event": "signup"},+ }+ # The first experiment is newer, and a session's metrics register in candidate+ # (newest-first) order, so the second experiment's metric falls past the patched+ # one-slot cap — in the batch and in a hypothetical single request alike.+ self._create_experiment(+ key="first-exp",+ name="First experiment",+ start_date=datetime(2025, 12, 15, tzinfo=UTC),+ metrics=[first_metric],+ )+ self._create_experiment(key="second-exp", name="Second experiment", metrics=[second_metric])++ self._create_recording()+ self._create_session_event(properties={"$feature_flag": "first-exp", "$feature_flag_response": "test"})+ self._create_session_event(+ timestamp="2026-01-01T10:03:00Z",+ properties={"$feature_flag": "second-exp", "$feature_flag_response": "control"},+ )+ self._create_session_event(event="purchase", timestamp="2026-01-01T10:09:00Z")+ self._create_session_event(event="signup", timestamp="2026-01-01T10:10:00Z")+ flush_persons_and_events()++ with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):+ response = self._post_session_contexts([SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ by_flag = {result["flag_key"]: result for result in response.json()["results"][0]["results"]}+ assert [hit["metric_uuid"] for hit in by_flag["first-exp"]["metrics_in_session"]] == [first_metric["uuid"]]+ assert by_flag["second-exp"]["metrics_in_session"] == []++ # Capped, but cached anyway: the single endpoint serves the batch's result without+ # recomputing, because a recompute under the same cap would drop the same metric.+ with patch("products.experiments.backend.session_context._compute_session_experiment_contexts") as compute:+ single = self._get_session_context()+ compute.assert_not_called()+ assert single.json()["results"] == response.json()["results"][0]["results"]+def test_batch_caps_candidates_per_day_chunk(self) -> None:# A newest-first candidate cap applied once over the whole batch's window can displace# an older experiment that a single request for an old recording would surface —