: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
feat(experiments): batch-prefetch replay session context on experiment tab (#73461)
Marcel Poelkeree0febaa5c2e
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex 847f84ccde77..cdbe1f0f5557 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -41,7 +41,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):effectiveMetricUuids,metricOptions,} = useValues(logic)- const { setSelectedVariantKey, setMetricSelected } = useActions(logic)+ const { setSelectedVariantKey, setMetricSelected, recordingsLoaded, recordingOpened } = useActions(logic)if (!isLaunched(experiment)) {return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>@@ -150,6 +150,8 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):logicKey={`experiment-${experiment.id}`}filters={recordingsFilters}updateSearchParams={false}+ onRecordingsLoaded={(recordings) => recordingsLoaded(recordings.map((recording) => recording.id))}+ onRecordingSelected={(recordingId) => recordingOpened(recordingId)}/></div></div>diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 35f16922e34a..428bf3f221a5 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -1,11 +1,15 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { Experiment, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'+import { experimentsSessionContextsCreate } from 'products/experiments/frontend/generated/api'+import { getViewRecordingFiltersForVariant } from '../utils'import { RETENTION_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'import { experimentReplayTabLogic } from './experimentReplayTabLogic'@@ -14,6 +18,10 @@ jest.mock('lib/utils/product-intents', () => ({addProductIntentForCrossSell: jest.fn().mockResolvedValue(null),}))+jest.mock('products/experiments/frontend/generated/api', () => ({+ experimentsSessionContextsCreate: jest.fn().mockResolvedValue({ results: [] }),+}))+const PURCHASE_METRIC = {kind: NodeKind.ExperimentMetric,metric_type: ExperimentMetricType.MEAN,@@ -68,6 +76,7 @@ describe('experimentReplayTabLogic', () => {// The facet reducer is persisted; clear so no test inherits another's selection.localStorage.clear()initKeaTests()+ ;(experimentsSessionContextsCreate as jest.Mock).mockClear()seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')seenTogetherSpy.mockResolvedValue(ALL_LINKABLE)logic = experimentReplayTabLogic({ experiment: EXPERIMENT })@@ -424,6 +433,52 @@ describe('experimentReplayTabLogic', () => {failed.unmount()})+ it('prefetches session contexts for a loaded recordings page when the flag is on', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EXPERIMENT_CONTEXT]: true })+ logic.actions.recordingsLoaded(['s1', 's2'])+ await expectLogic(logic).toFinishAllListeners()++ expect(experimentsSessionContextsCreate).toHaveBeenCalledWith(expect.any(String), {+ session_ids: ['s1', 's2'],+ })+ })++ it('re-warms the rest of the page when a recording is opened', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EXPERIMENT_CONTEXT]: true })++ // Opening before any page has loaded must not fire an empty batch (the backend 400s it).+ logic.actions.recordingOpened('s1')+ await expectLogic(logic).toFinishAllListeners()+ expect(experimentsSessionContextsCreate).not.toHaveBeenCalled()++ logic.actions.recordingsLoaded(['s1', 's2', 's3'])+ await expectLogic(logic).toFinishAllListeners()++ // The server-side cache TTL runs from prefetch time, so each open must re-warm the+ // page — without this, a user who watches one recording past the TTL opens every+ // later one cold. The opened id is excluded: the player is fetching it right now.+ logic.actions.recordingOpened('s2')+ await expectLogic(logic).toFinishAllListeners()++ expect(experimentsSessionContextsCreate).toHaveBeenCalledTimes(2)+ expect((experimentsSessionContextsCreate as jest.Mock).mock.calls[1][1].session_ids).toEqual(['s1', 's3'])+ })++ it('never prefetches for flag-disabled viewers, and caps a batch at the backend limit', async () => {+ // Ungated, every experiment-tab visit would fire the expensive ClickHouse scans for+ // viewers who can't even see the experiments box.+ logic.actions.recordingsLoaded(['s1'])+ await expectLogic(logic).toFinishAllListeners()+ expect(experimentsSessionContextsCreate).not.toHaveBeenCalled()++ // Over-cap ids must be sliced, not sent — the backend 400s the whole batch above its cap.+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EXPERIMENT_CONTEXT]: true })+ logic.actions.recordingsLoaded(Array.from({ length: 25 }, (_, index) => `session-${index}`))+ await expectLogic(logic).toFinishAllListeners()+ expect(experimentsSessionContextsCreate).toHaveBeenCalledTimes(1)+ expect((experimentsSessionContextsCreate as jest.Mock).mock.calls[0][1].session_ids).toHaveLength(20)+ })+it('offers saved/shared metrics in the facet, deduped by uuid', async () => {const savedMetric = {query: {diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex fec57e4dc224..365051e8c8ec 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -1,7 +1,10 @@-import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { teamLogic } from 'scenes/teamLogic'import {ExperimentMetric,@@ -12,6 +15,8 @@ import {} from '~/queries/schema/schema-general'import { Experiment, FilterLogicalOperator, RecordingUniversalFilters, UniversalFiltersGroupValue } from '~/types'+import { experimentsSessionContextsCreate } from 'products/experiments/frontend/generated/api'+import type { ExperimentIdType } from '../../../types'import type { ExperimentSavedMetric } from '../experimentLogic'import { getDefaultMetricTitle } from '../MetricsView/shared/utils'@@ -44,14 +49,20 @@ export interface ExperimentReplayMetricOption {unlinkableReason: string | null}+// Mirrors the backend's MAX_SESSION_CONTEXT_BATCH — ids beyond it would 400 the whole batch.+const SESSION_CONTEXT_PREFETCH_LIMIT = 20+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentProjectId: number | string // teamLogiclinkabilityLoaded: boolean // viewRecordingsLinkabilityLogicseenTogetherMapLoading: boolean // viewRecordingsLinkabilityLogicunlinkableEventNames: Set<string> // viewRecordingsLinkabilityLogiceffectiveMetricUuids: string[]effectiveVariantKey: string | nullexposureUnlinkable: boolean+ loadedSessionIds: string[]metricOptions: ExperimentReplayMetricOption[]recordingsFilters: RecordingUniversalFiltersselectedMetricUuids: string[]@@ -62,6 +73,15 @@ export interface experimentReplayTabLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicActions {+ prefetchSessionContexts: (sessionIds: string[]) => {+ sessionIds: string[]+ }+ recordingOpened: (sessionId: string) => {+ sessionId: string+ }+ recordingsLoaded: (sessionIds: string[]) => {+ sessionIds: string[]+ }setMetricSelected: (metricUuid: string,selected: boolean@@ -119,11 +139,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([values: [viewRecordingsLinkabilityLogic({ experiment: props.experiment }),['unlinkableEventNames', 'linkabilityLoaded', 'seenTogetherMapLoading'],+ featureFlagLogic,+ ['featureFlags'],+ teamLogic,+ ['currentProjectId'],],})),actions({setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),setMetricSelected: (metricUuid: string, selected: boolean) => ({ metricUuid, selected }),+ recordingsLoaded: (sessionIds: string[]) => ({ sessionIds }),+ recordingOpened: (sessionId: string) => ({ sessionId }),+ prefetchSessionContexts: (sessionIds: string[]) => ({ sessionIds }),}),reducers({// null = "All" (every exposed session, regardless of variant). Persisted (keyed per@@ -150,6 +177,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([: state.filter((uuid) => uuid !== metricUuid),},],+ // The playlist's most recently loaded page, kept so opening a recording can re-warm+ // the rest of the page's contexts.+ loadedSessionIds: [+ [] as string[],+ {+ recordingsLoaded: (_, { sessionIds }) => sessionIds,+ },+ ],}),selectors({variantKeys: [@@ -333,6 +368,51 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([},],}),+ listeners(({ values, actions, cache }) => ({+ // Prefetch experiment context for the freshly loaded page of recordings, so opening+ // any of them renders the player's experiments box straight from the server-side+ // cache. A session's context is independent of the list filters (it's per+ // session + viewer), so sessions overlapping across filter changes are already warm+ // and the endpoint skips them.+ recordingsLoaded: ({ sessionIds }) => {+ actions.prefetchSessionContexts(sessionIds)+ },+ // Re-warm the rest of the page whenever the user moves to another recording: the+ // server-side cache entries expire on a TTL that starts at prefetch time, so a page+ // prefetched once goes cold under a user who watches one recording for a while. The+ // endpoint skips warm sessions, so in the steady state a re-fire costs one request+ // and cache reads; only expired entries recompute. The opened recording is excluded —+ // the player is fetching it right now, and including it would compute it twice.+ recordingOpened: ({ sessionId }) => {+ actions.prefetchSessionContexts(values.loadedSessionIds.filter((id) => id !== sessionId))+ },+ prefetchSessionContexts: async ({ sessionIds }, breakpoint) => {+ if (!values.featureFlags[FEATURE_FLAGS.REPLAY_EXPERIMENT_CONTEXT] || sessionIds.length === 0) {+ return+ }+ // Debounce rapid filter churn — a superseded batch is cancelled at the breakpoint.+ await breakpoint(500)+ // Serialize behind any in-flight batch: its cache writes only land when it+ // finishes, so a batch fired concurrently would recompute the same sessions+ // instead of skipping them as warm. The breakpoint drops this run if a newer+ // prefetch arrived while it waited.+ while (cache.sessionContextPrefetch) {+ await cache.sessionContextPrefetch+ breakpoint()+ }+ const request = experimentsSessionContextsCreate(String(values.currentProjectId), {+ session_ids: sessionIds.slice(0, SESSION_CONTEXT_PREFETCH_LIMIT),+ }).catch(() => {+ // Best-effort prefetch — the player's own request is the fallback.+ })+ cache.sessionContextPrefetch = request+ try {+ await request+ } finally {+ cache.sessionContextPrefetch = null+ }+ },+ })),afterMount(() => {// Opening the tab is a session-replay cross-sell from experiments.void addProductIntentForCrossSell({diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex 660ffb3391d4..81a2344d6258 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -460,6 +460,13 @@ export interface SessionRecordingPlaylistLogicProps {type?: 'filters' | 'collection'filters?: RecordingUniversalFiltersonFiltersChange?: (filters: RecordingUniversalFilters) => void+ /** Called with each freshly loaded page of recordings (not the accumulated list). */+ onRecordingsLoaded?: (recordings: SessionRecordingType[]) => void+ /**+ * Called when a recording is selected (clicked, played next, or picked via the URL) —+ * not for the initial autoplayed recording, which is selected implicitly.+ */+ onRecordingSelected?: (recordingId: SessionRecordingType['id']) => voidpinnedFilters?: UniversalFiltersGrouppinnedRecordings?: (SessionRecordingType | string)[]onPinnedChange?: (recording: SessionRecordingType, pinned: boolean) => void@@ -1420,14 +1427,19 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicactions.loadSessionRecordings(direction)},- loadSessionRecordingsSuccess: () => {+ loadSessionRecordingsSuccess: ({ sessionRecordingsResponse }) => {actions.maybeLoadPropertiesForSessions(values.sessionRecordings)+ props.onRecordingsLoaded?.(sessionRecordingsResponse.results)},- setSelectedRecordingId: () => {+ setSelectedRecordingId: ({ id }) => {// Close filters when selecting a recordingactions.setIsFiltersExpanded(false)+ if (id) {+ props.onRecordingSelected?.(id)+ }+const recordingIndex = values.sessionRecordings.findIndex((s) => s.id === values.selectedRecordingId)// If recording not found in current list, reload with the new selected recordingdiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 83ddfa30b935..6cfc3df291a7 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -480,6 +480,40 @@ class CopyFlagsSustainedRateThrottle(PersonalApiKeyOrUserRateThrottle):rate = "300/hour"+# The batch session-context endpoint computes experiment context for up to 20 recordings per+# call, in up to several per-day ClickHouse scan sets — heavier than most ClickHouse endpoints+# — and its primary caller is the session-authenticated replay/experiment UI, which the+# ClickHouse*RateThrottle pair deliberately does not cover. PersonalApiKeyOrUserRateThrottle+# applies regardless of auth method. The UI fires at most one prefetch per user action (page+# load, filter change — debounced client-side — or recording open), and repeats hit the+# server-side cache, so these rates clear a whole project's worth of concurrent viewers while+# capping a scripted loop of cold batches.+class _SessionContextsRateThrottleBase(PersonalApiKeyOrUserRateThrottle):+ def get_cache_key(self, request: "Request", view: "APIView") -> str:+ # One bucket per project regardless of auth method. The parent idents personal-API-key+ # requests by key hash, so each minted key would get its own budget of this expensive+ # compute — the sum must be capped project-wide instead, the same reasoning as+ # ProjectSecretApiKeyTeamRateThrottle's team-wide bucket.+ team_id = self.safely_get_team_id_from_view(view)+ if team_id is not None:+ ident = team_id+ elif request.user.is_authenticated:+ ident = request.user.pk+ else:+ ident = self.get_ident(request)+ return self.cache_format % {"scope": self.scope, "ident": ident}+++class SessionContextsBurstRateThrottle(_SessionContextsRateThrottleBase):+ scope = "session_contexts_burst"+ rate = "60/minute"+++class SessionContextsSustainedRateThrottle(_SessionContextsRateThrottleBase):+ scope = "session_contexts_sustained"+ rate = "600/hour"++class _AIThrottleBase(UserRateThrottle):action_name: strdiff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.pyindex 11bc04335e81..290614b084d5 100644--- a/products/experiments/backend/metric_events.py+++ b/products/experiments/backend/metric_events.py@@ -1,13 +1,14 @@-"""Resolve which events an experiment's metrics count, and scan a session for them.+"""Resolve which events an experiment's metrics count, and scan sessions for them.A session recording can contain the events an experiment's metrics count. This module maps anexperiment's metrics (inline primary + secondary and saved/shared, via the shared-`metric_resolution` enumerator) to their concrete event/action sources, and scans one session-for those events. Data-warehouse sources have no session events, so metrics whose every source-is a data-warehouse node are marked non-linkable and skipped by the scan.+`metric_resolution` enumerator) to their concrete event/action sources, and scans a batch of+sessions for those events in one query. Data-warehouse sources have no session events, so+metrics whose every source is a data-warehouse node are marked non-linkable and skipped by+the scan.-Consumed by the additive `metrics_in_session` fields on the single-session `session_context`-endpoint.+Consumed by the additive `metrics_in_session` fields on the `session_context` /+`session_contexts` endpoints."""import logging@@ -161,6 +162,16 @@ class MetricHit:sources: tuple[MetricSourceHit, ...]+@dataclass(frozen=True)+class MetricScanResult:+ # session_id -> hits sorted by first occurrence; sessions with no matching events are omitted.+ hits_by_session: dict[str, list[MetricHit]]+ # Metric uuids refused at MAX_SCANNED_METRICS. Hits for these metrics are silently absent+ # from every session's list, so callers that cache per-session results need this set to+ # tell an incomplete result from a genuinely hitless one.+ dropped_metric_uuids: set[str]++def _node_signature(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str:"""A stable identity for a source node. Two nodes with the same signature match the same eventsand share one aggregate in the scan, so they can only ever render identical hits."""@@ -279,23 +290,24 @@ def _node_condition(node: MetricSourceNode, team: Team) -> ast.Expr:return condition-def scan_session_for_metric_events(+def scan_sessions_for_metric_events(team: Team,user: User,*,metric_sources: list[MetricEventSource],- session_id: str,+ session_ids: list[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.+) -> MetricScanResult:+ """Per session, the metrics with >=1 matching event, sorted by first occurrence — as+ MetricScanResult.hits_by_session. Sessions with no matching events are omitted.- 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.+ One scan computes every metric via conditional aggregation (countIf/minIf/groupArrayIf)+ grouped by session: a per-metric UNION ALL re-reads the sessions' 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.Each metric is aggregated twice over: once across all its sources (its own totals, an OR soan event matching two sources still counts once) and once per source (the breakdown that@@ -305,7 +317,9 @@ def scan_session_for_metric_events(Metrics with no hits are omitted. Duplicate metric uuids (a saved metric shared by severalexperiments) and metrics with identical source nodes (several experiments measuring thesame 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:+ call (the overflow is not an error: it is logged and returned as dropped_metric_uuids so+ callers can treat the affected sessions' results as incomplete). The cap counts metrics,+ not distinct sources: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.@@ -323,7 +337,7 @@ def scan_session_for_metric_events(# Aggregate groups, keyed by the sorted distinct source nodes they cover: one per metric (all# its sources) plus one per individual source. A single-source metric's two keys coincide.group_indexes: dict[tuple[str, ...], int] = {}- skipped_over_cap = 0+ dropped_metric_uuids: set[str] = set()skipped_breakdown_sources = 0def node_key(source: MetricSource) -> str:@@ -347,7 +361,7 @@ def scan_session_for_metric_events(if not metric_source.session_linkable or metric_source.metric_uuid in seen_uuids:continueif len(seen_uuids) >= MAX_SCANNED_METRICS:- skipped_over_cap += 1+ dropped_metric_uuids.add(metric_source.metric_uuid)continueseen_uuids.add(metric_source.metric_uuid)accepted.append(metric_source)@@ -364,23 +378,26 @@ def scan_session_for_metric_events(if not register_group((node_key(source),), capped=True):skipped_breakdown_sources += 1- if skipped_over_cap:- logger.warning(- "Metric scan for session %s capped at %s metrics; %s metrics not scanned",- session_id,+ if dropped_metric_uuids:+ # Info, not warning: metric-heavy teams hit this cap in steady state, and the batch+ # caller already declines to cache the affected sessions, so an on-demand recompute+ # restores the full set.+ logger.info(+ "Metric scan for sessions %s capped at %s metrics; %s metrics not scanned",+ session_ids,MAX_SCANNED_METRICS,- skipped_over_cap,+ len(dropped_metric_uuids),)if skipped_breakdown_sources:logger.warning(- "Metric scan for session %s capped at %s aggregate groups; per-source breakdown dropped for %s source(s)",- session_id,+ "Metric scan for sessions %s capped at %s aggregate groups; per-source breakdown dropped for %s source(s)",+ session_ids,MAX_AGGREGATE_GROUPS,skipped_breakdown_sources,)if not group_indexes:- return []+ return MetricScanResult(hits_by_session={}, dropped_metric_uuids=dropped_metric_uuids)# 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.@@ -388,7 +405,8 @@ def scan_session_for_metric_events(conditions = [deepcopy(conditions_by_node[node]) for node in key]return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]- select: list[ast.Expr] = []+ # Column 0 is the session_id the row aggregates over; each group's three aggregates follow.+ select: list[ast.Expr] = [ast.Alias(alias="session_id", expr=ast.Field(chain=["$session_id"]))]for key, index in group_indexes.items():select.append(ast.Alias(alias=f"count_{index}", expr=ast.Call(name="countIf", args=[group_condition(key)])))select.append(@@ -423,12 +441,13 @@ def scan_session_for_metric_events(query = ast.SelectQuery(select=select,select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ group_by=[ast.Field(chain=["session_id"])],where=ast.And(exprs=[ast.CompareOperation(- op=ast.CompareOperationOp.Eq,+ op=ast.CompareOperationOp.In,left=ast.Field(chain=["$session_id"]),- right=ast.Constant(value=session_id),+ right=ast.Constant(value=session_ids),),ast.CompareOperation(op=ast.CompareOperationOp.GtEq,@@ -452,77 +471,78 @@ def scan_session_for_metric_events(extra_kwargs["modifiers"] = shared_hogql.modifiersresponse = 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.- row = response.results[0] if response.results else None- if row is None:- return []-- def read_group(key: tuple[str, ...]) -> Optional[tuple[int, datetime, tuple[datetime, ...]]]:+ # Grouped by session, so a session with no matching events yields no row at all; within a+ # row a metric with no matches shows count 0 (and an epoch minIf), so the count guards the+ # timestamps. Column 0 is the session_id, so a group at `index` starts at 1 + index * 3.+ def read_group(row: list, key: tuple[str, ...]) -> Optional[tuple[int, datetime, tuple[datetime, ...]]]:index = group_indexes.get(key)if index is None:return None- event_count = row[index * 3]+ event_count = row[index * 3 + 1]if not event_count:return None- return int(event_count), row[index * 3 + 1], tuple(row[index * 3 + 2])-- hits: list[MetricHit] = []- for metric_source in accepted:- totals = read_group(metric_group_key(metric_source))- if totals is None:- continue- event_count, first_timestamp, timestamps = totals- # A funnel can list the same event as several steps (an "N-th occurrence" funnel: the same- # activation event repeated N times). Those steps share one aggregate group, so reading the- # group per step would echo the same events under every step, and a single occurrence would- # read as a completed N-step funnel. Assign the group's occurrences positionally instead:- # the k-th such step maps to the k-th occurrence, so it fires only once the event has fired- # k+1 times. Only funnel steps are positional — a ratio reusing one event on both sides- # still legitimately counts it on each side, so its identical sources keep echoing.- repeated_step_nodes = Counter(- node_key(source) for source in metric_source.sources if source.role == MetricSourceRole.STEP- )- step_rank: dict[str, int] = {}- source_hits: list[MetricSourceHit] = []- for source in metric_source.sources:- source_totals = read_group((node_key(source),))- if source_totals is None:+ return int(event_count), row[index * 3 + 2], tuple(row[index * 3 + 3])++ hits_by_session: dict[str, list[MetricHit]] = {}+ for row in response.results or []:+ hits: list[MetricHit] = []+ for metric_source in accepted:+ totals = read_group(row, metric_group_key(metric_source))+ if totals is None:continue- source_count, source_first, source_timestamps = source_totals- node_sig = node_key(source)- if repeated_step_nodes[node_sig] > 1:- rank = step_rank.get(node_sig, 0)- step_rank[node_sig] = rank + 1- # A step is reached once the event has fired more times than its rank; drop only the- # steps the event never reached (gauge that on the true count, not the seek-point- # tuple). Seek points are capped at MAX_METRIC_EVENT_TIMESTAMPS, so a step reached- # past the cap (a >cap-step funnel of one event) keeps its place and points at the- # last available seek point rather than vanishing.- if rank >= source_count:+ event_count, first_timestamp, timestamps = totals+ # A funnel can list the same event as several steps (an "N-th occurrence" funnel: the same+ # activation event repeated N times). Those steps share one aggregate group, so reading the+ # group per step would echo the same events under every step, and a single occurrence would+ # read as a completed N-step funnel. Assign the group's occurrences positionally instead:+ # the k-th such step maps to the k-th occurrence, so it fires only once the event has fired+ # k+1 times. Only funnel steps are positional — a ratio reusing one event on both sides+ # still legitimately counts it on each side, so its identical sources keep echoing.+ repeated_step_nodes = Counter(+ node_key(source) for source in metric_source.sources if source.role == MetricSourceRole.STEP+ )+ step_rank: dict[str, int] = {}+ source_hits: list[MetricSourceHit] = []+ for source in metric_source.sources:+ source_totals = read_group(row, (node_key(source),))+ if source_totals is None:continue- occurrence = source_timestamps[min(rank, len(source_timestamps) - 1)]- source_count, source_first, source_timestamps = 1, occurrence, (occurrence,)- source_hits.append(- MetricSourceHit(- role=source.role,- name=source.name,- index=source.index,- total=source.total,- event_count=source_count,- first_timestamp=source_first,- timestamps=source_timestamps,+ source_count, source_first, source_timestamps = source_totals+ node_sig = node_key(source)+ if repeated_step_nodes[node_sig] > 1:+ rank = step_rank.get(node_sig, 0)+ step_rank[node_sig] = rank + 1+ # A step is reached once the event has fired more times than its rank; drop only the+ # steps the event never reached (gauge that on the true count, not the seek-point+ # tuple). Seek points are capped at MAX_METRIC_EVENT_TIMESTAMPS, so a step reached+ # past the cap (a >cap-step funnel of one event) keeps its place and points at the+ # last available seek point rather than vanishing.+ if rank >= source_count:+ continue+ occurrence = source_timestamps[min(rank, len(source_timestamps) - 1)]+ source_count, source_first, source_timestamps = 1, occurrence, (occurrence,)+ source_hits.append(+ MetricSourceHit(+ role=source.role,+ name=source.name,+ index=source.index,+ total=source.total,+ event_count=source_count,+ first_timestamp=source_first,+ timestamps=source_timestamps,+ )+ )+ hits.append(+ MetricHit(+ metric_uuid=metric_source.metric_uuid,+ metric_name=metric_source.metric_name,+ event_count=event_count,+ first_timestamp=first_timestamp,+ timestamps=timestamps,+ sources=tuple(source_hits),))- hits.append(- MetricHit(- metric_uuid=metric_source.metric_uuid,- metric_name=metric_source.metric_name,- event_count=event_count,- first_timestamp=first_timestamp,- timestamps=timestamps,- sources=tuple(source_hits),- )- )- hits.sort(key=lambda hit: hit.first_timestamp)- return hits+ if hits:+ hits.sort(key=lambda hit: hit.first_timestamp)+ hits_by_session[str(row[0])] = hits+ return MetricScanResult(hits_by_session=hits_by_session, dropped_metric_uuids=dropped_metric_uuids)diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 009d5799aef2..6975a1527d48 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -43,6 +43,7 @@ from products.experiments.backend.models.experiment import (experiment_has_legacy_metrics,)from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICES+from products.experiments.backend.session_context import MAX_SESSION_CONTEXT_BATCHfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_error@@ -1616,3 +1617,31 @@ class ExperimentSessionContextResponseSerializer(serializers.Serializer):class ExperimentActivityQuerySerializer(serializers.Serializer):limit = serializers.IntegerField(required=False, default=10, min_value=1, help_text="Number of items per page")page = serializers.IntegerField(required=False, default=1, min_value=1, help_text="Page number")+++class ExperimentSessionContextsRequestSerializer(serializers.Serializer):+ """Request body for the batch session-context endpoint."""++ session_ids = serializers.ListField(+ child=serializers.CharField(allow_blank=False, help_text="ID of one session recording."),+ min_length=1,+ max_length=MAX_SESSION_CONTEXT_BATCH,+ help_text=(+ f"IDs of the session recordings to resolve experiment context for, at most "+ f"{MAX_SESSION_CONTEXT_BATCH} per request. Duplicates are ignored."+ ),+ )+++class ExperimentSessionContextsResponseSerializer(serializers.Serializer):+ """Experiment/variant context for a batch of session recordings."""++ results = ExperimentSessionContextResponseSerializer(+ many=True,+ help_text=(+ "Per-session experiment context, in the order the session IDs were requested. Sessions whose "+ "recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, "+ "as are sessions beyond the batch's recording-day budget (only the most recent days are computed). "+ "Fetch omitted sessions individually via the single-session endpoint."+ ),+ )diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex d3bb25e7b393..6642ee92d37b 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -34,7 +34,12 @@ from posthog.models.activity_logging.activity_page import ActivityLogPaginatedRefrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle+from posthog.rate_limit import (+ ClickHouseBurstRateThrottle,+ ClickHouseSustainedRateThrottle,+ SessionContextsBurstRateThrottle,+ SessionContextsSustainedRateThrottle,+)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputs@@ -64,6 +69,8 @@ from products.experiments.backend.presentation.serializers import (ExperimentMetricsRecalculationSerializer,ExperimentSerializer,ExperimentSessionContextResponseSerializer,+ ExperimentSessionContextsRequestSerializer,+ ExperimentSessionContextsResponseSerializer,ExperimentWriteSerializer,RecalculateMetricsRequestSerializer,RunningTimeCalculationInputSerializer,@@ -87,7 +94,7 @@ from products.experiments.backend.running_time_calculator import (calculate_variance,calculate_variance_from_stats,)-from products.experiments.backend.session_context import get_session_experiment_context+from products.experiments.backend.session_context import get_session_experiment_context, get_session_experiment_contextsfrom products.experiments.backend.temporal.models import (ExperimentMetricsRecalculationWorkflowInputs as MetricsRecalcInputs,)@@ -1288,6 +1295,50 @@ class EnterpriseExperimentsViewSet(serializer = ExperimentSessionContextResponseSerializer({"session_id": session_id, "results": items})return Response(serializer.data)+ @validated_request(+ request_serializer=ExperimentSessionContextsRequestSerializer,+ responses={200: OpenApiResponse(response=ExperimentSessionContextsResponseSerializer)},+ )+ @action(+ methods=["POST"],+ detail=False,+ url_path="session_contexts",+ required_scopes=["experiment:read", "session_recording:read"],+ # Not the ClickHouse* pair the single-session action uses: that pair only limits+ # personal-API-key traffic, and this endpoint's primary caller is the+ # session-authenticated web app.+ throttle_classes=[SessionContextsBurstRateThrottle, SessionContextsSustainedRateThrottle],+ )+ def session_contexts(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ """Resolve experiment context for a batch of session recordings.++ Batch variant of `session_context`, used to prefetch the replay player's experiments+ box for a whole recordings list in one request. POST because the id list doesn't fit a+ query string; the endpoint only reads. Already-computed sessions are served from (and+ cold ones written to) the same short-lived per-viewer cache the single-session endpoint+ uses, so opening any prefetched recording renders its context instantly. Sessions whose+ recording metadata doesn't exist yet are omitted from the response, as are sessions+ beyond the batch's recording-day budget (each distinct recording day costs its own set+ of ClickHouse scans, so only the most recent days are computed per request).+ """+ session_ids: list[str] = request.validated_data["session_ids"]++ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Reading session experiment context requires session replay access.")++ # detail=False actions skip the automatic list-action ACL filtering, so filter here —+ # private experiments must not leak into another user's session context.+ experiments = self.user_access_control.filter_queryset_by_access_level(+ Experiment.objects.filter(team_id=self.team.pk)+ )+ contexts = get_session_experiment_contexts(+ team=self.team, session_ids=session_ids, experiments=experiments, user=cast(User, request.user)+ )+ serializer = ExperimentSessionContextsResponseSerializer(+ {"results": [{"session_id": session_id, "results": items} for session_id, items in contexts.items()]}+ )+ return Response(serializer.data)+def _serialize_recalculation(recalc: ExperimentMetricsRecalculation, active_run: dict | None = None) -> dict:results = get_run_results(recalc)diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex 6a95b7408eaa..7e6c028002f3 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -23,7 +23,7 @@ import loggingimport contextvarsfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass-from datetime import datetime, timedelta+from datetime import date, datetime, timedeltafrom functools import partialfrom typing import Optional@@ -44,7 +44,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents, uuidv7_session_lower_boundfrom posthog.utils import get_safe_cachefrom products.cohorts.backend.models.cohort import Cohort@@ -58,7 +58,7 @@ from products.experiments.backend.metric_events import (MetricHit,SharedHogQLDatabase,resolve_metric_events,- scan_session_for_metric_events,+ scan_sessions_for_metric_events,)from products.experiments.backend.models.experiment import Experiment@@ -76,8 +76,20 @@ 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+# across users. That per-viewer key is also why the TTL is an acceptable ACL boundary: there+# is no cross-user leak to begin with, the only exposure is a bounded revocation lag for a+# viewer who legitimately had access moments before — matching how other short-TTL caches in+# this codebase behave on permission changes. Per-endpoint ACL-version invalidation would add+# complexity and a lookup to a path that exists to cut latency.+SESSION_CONTEXT_CACHE_TTL = 10 * 60+# Hard cap on the batch endpoint's id list. A playlist page holds 20 recordings, and every+# extra session widens the grouped scans; anything larger should arrive as separate batches.+MAX_SESSION_CONTEXT_BATCH = 20+# Each distinct recording day in a batch runs its own set of scans, so ids scattered across+# many days would fan one throttled HTTP request out into dozens of ClickHouse queries. The+# most recent days win (recordings lists sort by recency); sessions beyond the budget are+# omitted — never cached — so the single-session endpoint computes them on demand.+MAX_SESSION_CONTEXT_BATCH_DAYS = 5@dataclass(frozen=True)@@ -109,6 +121,35 @@ class ExperimentSessionContextItem:metrics_in_session: list[MetricHit]+@dataclass(frozen=True)+class _SessionWindow:+ """One session's recording bounds — the unit the batch compute fans out over."""++ session_id: str+ recording_start: datetime+ recording_end: datetime+++@dataclass(frozen=True)+class _ResolvedCandidates:+ """The batch's overlapping experiments and their resolved exposure metadata, computed once+ over the union of the sessions' recording windows and shared by every day-chunk. The+ capped candidate slice is per chunk, not here — see _compute_session_experiment_contexts."""++ overlapping: QuerySet[Experiment]+ flag_key_by_id: dict[int, str]+ variant_keys_by_id: dict[int, set[str]]+ batchable_ids: set[int]+ all_variant_keys: set[str]+ branch_meta: list[tuple[int, "_ResolvedExposure", set[str]]]+++def _cache_key(team: Team, user: User, session_id: str) -> str:+ # The version segment must be bumped whenever the cached dataclasses change shape: entries are+ # pickled, so a deploy would otherwise restore instances missing the new fields.+ return f"experiment_session_context_v2_{team.pk}_{user.pk}_{session_id}"++def get_session_experiment_context(team: Team, session_id: str, experiments: QuerySet[Experiment], user: User) -> Optional[list[ExperimentSessionContextItem]]:@@ -124,56 +165,149 @@ def get_session_experiment_context(a recording doesn't re-run the ClickHouse scans. "Recording not found" is not cached: therecording may simply still be ingesting."""- # The version segment must be bumped whenever the cached dataclasses change shape: entries are- # pickled, so a deploy would otherwise restore instances missing the new fields.- cache_key = f"experiment_session_context_v2_{team.pk}_{user.pk}_{session_id}"+ cache_key = _cache_key(team, user, 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+ window = _SessionWindow(+ session_id=session_id, recording_start=metadata["start_time"], recording_end=metadata["end_time"]+ )+ # fail_open=False: unlike the best-effort batch prefetch, the player's request must surface+ # a scan failure as an error, never as a false "recording not found".+ computed, _ = _compute_session_experiment_contexts(team, [window], experiments, user, fail_open=False)+ items = computed[session_id]+ # A capped single session is still cached: with one session there is no batch union, so a+ # recompute would drop the same metrics again and caching the capped result loses nothing.+ cache.set(cache_key, items, timeout=SESSION_CONTEXT_CACHE_TTL)+ return items+++def get_session_experiment_contexts(+ team: Team, session_ids: list[str], experiments: QuerySet[Experiment], user: User+) -> dict[str, list[ExperimentSessionContextItem]]:+ """Batch variant of get_session_experiment_context: session_id -> items, in input order.++ Reads and writes the same per-(team, viewer, session) cache entries as the single-session+ endpoint — already-warm sessions are skipped, cold ones are computed in shared scans and+ written back so a later single-session request hits cache. Sessions whose recording+ metadata doesn't exist (yet) are omitted and never cached, mirroring the single endpoint's+ not-found rule; so are ids without a parseable uuidv7 timestamp, whose metadata lookup+ would 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.+ """+ unique_ids = list(dict.fromkeys(session_ids))+ results: dict[str, list[ExperimentSessionContextItem]] = {}+ cold_ids: list[str] = []+ for session_id in unique_ids:+ cached = get_safe_cache(_cache_key(team, user, session_id))+ if cached is not None:+ results[session_id] = cached+ else:+ cold_ids.append(session_id)++ if cold_ids:+ # Bounded below by the batch's oldest uuidv7-derived session start (with clock-skew+ # slack); ids with no usable bound are excluded from the lookup entirely so one bad id+ # can't unbound the scan. An id that defeats or lacks the bound is simply not found+ # here and never cached as absent, so the single-session endpoint — whose lookup falls+ # back to an unbounded scan — still resolves it on demand.+ bounded_ids, lower_bound = _bounded_metadata_ids(cold_ids)+ metadata_by_id = SessionReplayEvents().get_group_metadata(+ bounded_ids, team, recordings_min_timestamp=lower_bound+ )+ windows = [+ _SessionWindow(+ session_id=session_id,+ recording_start=metadata["start_time"],+ recording_end=metadata["end_time"],+ )+ for session_id, metadata in metadata_by_id.items()+ if metadata is not None+ ]+ computed, capped_session_ids = _compute_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.+ 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)++ return {session_id: results[session_id] for session_id in unique_ids if session_id in results}+++def _bounded_metadata_ids(session_ids: list[str]) -> tuple[list[str], Optional[datetime]]:+ """The session ids whose embedded uuidv7 timestamp yields a metadata-scan lower bound+ (with clock-skew slack), and the oldest of those bounds. Ids without a usable bound are+ excluded rather than queried: keeping one in would force the whole batch's metadata scan+ unbounded across the table's retained date range. The batch is best-effort, so such an+ id (rare legacy formats, or garbage) is simply omitted — the single-session endpoint,+ whose lookup falls back to an unbounded scan, still resolves it on demand."""+ bounds_by_id = {+ session_id: bound for session_id in session_ids if (bound := uuidv7_session_lower_bound(session_id)) is not None+ }+ if not bounds_by_id:+ return [], None+ return list(bounds_by_id), min(bounds_by_id.values())- recording_start = metadata["start_time"]- recording_end = metadata["end_time"]- # Launched experiments whose run window overlaps the recording. Archived experiments are- # kept on purpose: the session really saw their variant while they ran.+def _chunk_windows_by_recording_day(windows: list[_SessionWindow]) -> list[list[_SessionWindow]]:+ """Group sessions by recording start day. Each chunk scans one contiguous timestamp range,+ so a batch mixing old and new recordings doesn't widen every scan to the full span and+ destroy the events table's date-partition pruning."""+ by_day: dict[date, list[_SessionWindow]] = {}+ for window in windows:+ by_day.setdefault(window.recording_start.date(), []).append(window)+ return [by_day[day] for day in sorted(by_day)]+++def _compute_session_experiment_contexts(+ team: Team,+ windows: list[_SessionWindow],+ experiments: QuerySet[Experiment],+ user: User,+ *,+ 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."""+ if not windows:+ return {}, set()++ union_start = min(window.recording_start for window in windows)+ union_end = max(window.recording_end for window in windows)++ # Launched experiments whose run window overlaps any of the recordings (the union of the+ # windows here; each session re-checks its own bounds when surfacing). Archived experiments+ # are kept on purpose: the session really saw their variant while they ran.overlapping = (experiments.filter(team_id=team.pk).exclude(deleted=True)- .filter(start_date__isnull=False, start_date__lte=recording_end)- .filter(Q(end_date__isnull=True) | Q(end_date__gte=recording_start))+ .filter(start_date__isnull=False, start_date__lte=union_end)+ .filter(Q(end_date__isnull=True) | Q(end_date__gte=union_start)).select_related("feature_flag"))- # The stamped-property query needs one column per flag, so its candidate set must be capped;- # newest-first keeps the slice deterministic and biased toward the most relevant experiments.- candidates = list(overlapping.order_by("-start_date")[:MAX_CANDIDATE_EXPERIMENTS])- if not candidates:- return []-- window_start = recording_start - EVENT_WINDOW_SLACK- window_end = recording_end + EVENT_WINDOW_SLACK-# Every overlapping experiment's flag key (uncapped — the rescue below must be able to see- # beyond the candidate cap), its exposure criteria, and its defined variant names. Filtering- # the exposure queries to these bounds their cardinality by real configuration: sessions call- # plenty of non-experiment flags, and event payloads can carry arbitrary keys/variants.+ # beyond the candidate cap), its exposure criteria, its defined variant names, and its run+ # window (so each day-chunk can pick its own candidate slice below). Filtering the exposure+ # queries to these bounds their cardinality by real configuration: sessions call plenty of+ # non-experiment flags, and event payloads can carry arbitrary keys/variants.flag_meta = list(overlapping.order_by("-start_date").values_list(- "id", "feature_flag__key", "feature_flag__filters", "exposure_criteria"+ "id", "feature_flag__key", "feature_flag__filters", "exposure_criteria", "start_date", "end_date"))+ if not flag_meta:+ return {window.session_id: [] for window in windows}, set()# Each experiment's exposure criteria resolve (through the shared helpers) to what counts# as its exposure event and which property carries the variant. Experiments with the plain# default shape take their exposure moment straight from the shared flag-evaluations query;@@ -184,7 +318,7 @@ def _compute_session_experiment_context(batchable_ids: set[int] = set()all_variant_keys: set[str] = set()branch_meta: list[tuple[int, _ResolvedExposure, set[str]]] = []- for experiment_id, flag_key, filters, exposure_criteria in flag_meta:+ for experiment_id, flag_key, filters, exposure_criteria, _start_date, _end_date in flag_meta:variant_keys = _variant_keys_from_filters(filters)if not variant_keys:continue@@ -198,15 +332,49 @@ def _compute_session_experiment_context(branch_meta.append((experiment_id, resolution, variant_keys))if not flag_key_by_id:# No overlapping experiment defines variants, so nothing could surface a variant seen.- return []+ return {window.session_id: [] for window in windows}, set()++ chunks = _chunk_windows_by_recording_day(windows)+ if len(chunks) > MAX_SESSION_CONTEXT_BATCH_DAYS:+ # Ascending day order, so the slice keeps the most recent days' chunks. The dropped+ # sessions are omitted from the result (never cached as anything).+ dropped = [window.session_id for chunk in chunks[:-MAX_SESSION_CONTEXT_BATCH_DAYS] for window in chunk]+ logger.warning(+ "Session-context batch spans more than %s recording days; omitting sessions %s",+ MAX_SESSION_CONTEXT_BATCH_DAYS,+ dropped,+ )+ chunks = chunks[-MAX_SESSION_CONTEXT_BATCH_DAYS:]++ # The stamped-property query needs one column per flag, so each chunk's candidate set must+ # be capped; newest-first keeps a slice deterministic and biased toward the most relevant+ # experiments. Capping per chunk — against the chunk's own recording window — means a batch+ # mixing old and new recordings surfaces the same experiments N single-session requests+ # would: a global slice over the union window could displace an older chunk's experiments+ # behind newer ones, and stamped-only evidence is never rescued.+ candidate_ids_by_chunk: list[list[int]] = []+ for chunk in chunks:+ chunk_start = min(window.recording_start for window in chunk)+ chunk_end = max(window.recording_end for window in chunk)+ candidate_ids_by_chunk.append(+ [+ experiment_id+ for experiment_id, _flag_key, _filters, _criteria, start_date, end_date in flag_meta+ if start_date is not None and start_date <= chunk_end and (end_date is None or end_date >= chunk_start)+ ][:MAX_CANDIDATE_EXPERIMENTS]+ )+ all_candidate_ids = {experiment_id for chunk_ids in candidate_ids_by_chunk for experiment_id in chunk_ids}+ if not all_candidate_ids:+ return {window.session_id: [] for chunk in chunks for window in chunk}, set()+ experiments_by_id = {experiment.pk: experiment for experiment in overlapping.filter(id__in=all_candidate_ids)}# 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.+ # and every day-chunk. 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@@ -222,6 +390,54 @@ def _compute_session_experiment_context(modifiers=hogql_modifiers,)+ resolved = _ResolvedCandidates(+ overlapping=overlapping,+ flag_key_by_id=flag_key_by_id,+ variant_keys_by_id=variant_keys_by_id,+ batchable_ids=batchable_ids,+ all_variant_keys=all_variant_keys,+ branch_meta=branch_meta,+ )++ results: dict[str, list[ExperimentSessionContextItem]] = {}+ capped_session_ids: set[str] = set()+ for chunk, candidate_ids in zip(chunks, candidate_ids_by_chunk):+ candidates = [+ experiments_by_id[experiment_id] for experiment_id in candidate_ids if experiment_id in experiments_by_id+ ]+ if not candidates:+ # No experiment overlaps this chunk's recordings — the same empty answer a+ # single-session request would compute (and cache) without running any scan.+ results.update({window.session_id: [] for window in chunk})+ continue+ try:+ chunk_results, chunk_capped = _compute_chunk_contexts(team, user, shared_hogql, resolved, chunk, candidates)+ results.update(chunk_results)+ capped_session_ids |= chunk_capped+ except Exception:+ if not fail_open:+ raise+ # Best-effort batch: one pathological chunk must not take down the others. Its+ # sessions are omitted (and never cached), so they can still compute on demand.+ logger.exception(+ "Session-context scan failed for sessions %s; omitting them from the batch",+ [window.session_id for window in chunk],+ )+ return results, capped_session_ids+++def _compute_chunk_contexts(+ team: Team,+ user: User,+ shared_hogql: SharedHogQLDatabase,+ resolved: _ResolvedCandidates,+ windows: list[_SessionWindow],+ candidates: list[Experiment],+) -> tuple[dict[str, list[ExperimentSessionContextItem]], set[str]]:+ session_ids = [window.session_id for window in windows]+ window_start = min(window.recording_start for window in windows) - EVENT_WINDOW_SLACK+ window_end = max(window.recording_end for window in windows) + EVENT_WINDOW_SLACK+# 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.@@ -230,11 +446,11 @@ def _compute_session_experiment_context(team,user,shared_hogql,- session_id,+ session_ids,window_start,window_end,- set(flag_key_by_id.values()),- all_variant_keys,+ set(resolved.flag_key_by_id.values()),+ resolved.all_variant_keys,)# 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@@ -245,14 +461,21 @@ def _compute_session_experiment_context(team,user,shared_hogql,- session_id,+ session_ids,window_start,window_end,- branch_meta[:MAX_CANDIDATE_EXPERIMENTS],+ resolved.branch_meta[:MAX_CANDIDATE_EXPERIMENTS],)candidate_keys = {experiment.feature_flag.key for experiment in candidates}query_stamped = partial(- _query_stamped_flag_properties, team, user, shared_hogql, session_id, candidate_keys, window_start, window_end+ _query_stamped_flag_properties,+ team,+ user,+ shared_hogql,+ session_ids,+ candidate_keys,+ window_start,+ window_end,)# The three scans are independent given the pre-rescue candidate set (only the rescue@@ -274,110 +497,161 @@ def _compute_session_experiment_context(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)+ # Per-session exposure evidence keyed by experiment id: batchable experiments read the+ # shared flag-evaluations query, the rest their own union branch.+ exposures: dict[str, dict[int, list[tuple[str, datetime]]]] = {}+ for session_id in session_ids:+ session_flag_evaluations = flag_evaluations.get(session_id, {})+ exposures[session_id] = {+ experiment_id: session_flag_evaluations[flag_key]+ for experiment_id, flag_key in resolved.flag_key_by_id.items()+ if experiment_id in resolved.batchable_ids and flag_key in session_flag_evaluations+ }+ exposures[session_id].update(branch_exposures.get(session_id, {}))# 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 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}+ # experiments a session in the chunk demonstrably called.+ evidenced_keys: set[str] = set()+ for session_id in session_ids:+ evidenced_keys |= set(flag_evaluations.get(session_id, {}))+ evidenced_keys |= {resolved.flag_key_by_id[experiment_id] for experiment_id in exposures[session_id]}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, shared_hogql, session_id, rescued_keys, window_start, window_end)- )-- surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]] = []- for experiment in candidates:- flag_key = experiment.feature_flag.key- # Only the flag's defined variant keys count, mirroring the `variant IN variants` filter in- # build_common_exposure_conditions: a non-enrolled user's flag evaluation captures- # `$feature_flag_response: false`, which must not surface as a variant named "false".- defined_variants = variant_keys_by_id.get(experiment.pk, set())- exposure_rows = [row for row in exposures.get(experiment.pk, []) if row[0] in defined_variants]- flag_rows = [row for row in flag_evaluations.get(flag_key, []) if row[0] in defined_variants]- stamped_values = [value for value in stamped.get(flag_key, []) if value in defined_variants]- variants_seen = sorted(- {variant for variant, _ in exposure_rows} | {variant for variant, _ in flag_rows} | set(stamped_values)+ candidates = candidates + list(resolved.overlapping.filter(feature_flag__key__in=sorted(rescued_keys)))+ rescued_stamped = _query_stamped_flag_properties(+ team, user, shared_hogql, session_ids, rescued_keys, window_start, window_end)- if not variants_seen:- continue-- first_exposure_timestamp: Optional[datetime] = None- if exposure_rows:- variant, first_exposure_timestamp = min(exposure_rows, key=lambda row: row[1])- elif flag_rows:- # The session was demonstrably served this variant, but no event matched the- # experiment's exposure criteria — so there is no exposure moment to point at.- variant = min(flag_rows, key=lambda row: row[1])[0]- else:- variant = variants_seen[0]-- surfaced.append((experiment, variant, variants_seen, first_exposure_timestamp))-- # Only the experiments that actually surfaced (typically 1–3, not the candidate cap) get- # their metrics scanned. One scan covers them all — shared saved metrics dedupe by uuid- # inside the scan — and each experiment claims its own metrics' hits back by uuid.- # 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.+ for session_id, values_by_key in rescued_stamped.items():+ stamped.setdefault(session_id, {}).update(values_by_key)++ surfaced_by_session: dict[str, list[tuple[Experiment, str, list[str], Optional[datetime]]]] = {}+ for window in windows:+ session_id = window.session_id+ session_exposures = exposures.get(session_id, {})+ session_flag_evaluations = flag_evaluations.get(session_id, {})+ session_stamped = stamped.get(session_id, {})+ surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]] = []+ for experiment in candidates:+ # Candidates overlap the union of the batch's recording windows; re-check this+ # session's own bounds so a batch surfaces exactly what N single requests would.+ if experiment.start_date is None or experiment.start_date > window.recording_end:+ continue+ if experiment.end_date is not None and experiment.end_date < window.recording_start:+ continue+ flag_key = experiment.feature_flag.key+ # Only the flag's defined variant keys count, mirroring the `variant IN variants` filter in+ # build_common_exposure_conditions: a non-enrolled user's flag evaluation captures+ # `$feature_flag_response: false`, which must not surface as a variant named "false".+ defined_variants = resolved.variant_keys_by_id.get(experiment.pk, set())+ exposure_rows = [row for row in session_exposures.get(experiment.pk, []) if row[0] in defined_variants]+ flag_rows = [row for row in session_flag_evaluations.get(flag_key, []) if row[0] in defined_variants]+ stamped_values = [value for value in session_stamped.get(flag_key, []) if value in defined_variants]+ variants_seen = sorted(+ {variant for variant, _ in exposure_rows} | {variant for variant, _ in flag_rows} | set(stamped_values)+ )+ if not variants_seen:+ continue++ first_exposure_timestamp: Optional[datetime] = None+ if exposure_rows:+ variant, first_exposure_timestamp = min(exposure_rows, key=lambda row: row[1])+ elif flag_rows:+ # The session was demonstrably served this variant, but no event matched the+ # experiment's exposure criteria — so there is no exposure moment to point at.+ variant = min(flag_rows, key=lambda row: row[1])[0]+ else:+ variant = variants_seen[0]++ 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.sources_by_experiment: dict[int, list[MetricEventSource]] = {}- session_hits: dict[str, MetricHit] = {}+ hits_by_session: dict[str, dict[str, MetricHit]] = {}+ dropped_metric_uuids: set[str] = set()try:- sources_by_experiment = {experiment.pk: resolve_metric_events(experiment) for experiment, *_ in surfaced}+ for session_surfaced in surfaced_by_session.values():+ for experiment, *_ in session_surfaced:+ if experiment.pk not in sources_by_experiment:+ sources_by_experiment[experiment.pk] = resolve_metric_events(experiment)all_sources = [source for sources in sources_by_experiment.values() for source in sources]if all_sources:- session_hits = {- hit.metric_uuid: hit- for hit in scan_session_for_metric_events(- team,- user,- metric_sources=all_sources,- session_id=session_id,- window_start=window_start,- window_end=window_end,- shared_hogql=shared_hogql,- )+ scan = scan_sessions_for_metric_events(+ team,+ user,+ metric_sources=all_sources,+ session_ids=session_ids,+ window_start=window_start,+ window_end=window_end,+ shared_hogql=shared_hogql,+ )+ dropped_metric_uuids = scan.dropped_metric_uuids+ hits_by_session = {+ session_id: {hit.metric_uuid: hit for hit in hits} for session_id, hits in scan.hits_by_session.items()}except Exception:- logger.exception("Metric-event scan failed for session %s; returning context without metric hits", session_id)+ logger.exception("Metric-event scan failed for sessions %s; returning context without metric hits", session_ids)sources_by_experiment = {}- session_hits = {}-- items: list[ExperimentSessionContextItem] = []- for experiment, variant, variants_seen, first_exposure_timestamp in surfaced:- metrics_in_session = sorted(- {- source.metric_uuid: session_hits[source.metric_uuid]+ hits_by_session = {}+ dropped_metric_uuids = set()++ capped_session_ids: set[str] = set()+ if dropped_metric_uuids:+ capped_session_ids = {+ session_id+ for session_id, session_surfaced in surfaced_by_session.items()+ if any(+ source.metric_uuid in dropped_metric_uuids+ for experiment, *_ in session_surfacedfor source in sources_by_experiment.get(experiment.pk, [])- if source.metric_uuid in session_hits- }.values(),- key=lambda hit: hit.first_timestamp,- )- items.append(- ExperimentSessionContextItem(- experiment_id=experiment.pk,- experiment_name=experiment.name,- flag_key=experiment.feature_flag.key,- variant=variant,- variants_seen=variants_seen,- multiple_variants=len(variants_seen) > 1,- first_exposure_timestamp=first_exposure_timestamp,- experiment_start_date=experiment.start_date,- experiment_end_date=experiment.end_date,- metrics_in_session=metrics_in_session,)- )-- return sorted(items, key=lambda item: item.experiment_name.lower())+ }++ results: dict[str, list[ExperimentSessionContextItem]] = {}+ for session_id, session_surfaced in surfaced_by_session.items():+ session_hits = hits_by_session.get(session_id, {})+ items: list[ExperimentSessionContextItem] = []+ for experiment, variant, variants_seen, first_exposure_timestamp in session_surfaced:+ metrics_in_session = sorted(+ {+ source.metric_uuid: session_hits[source.metric_uuid]+ for source in sources_by_experiment.get(experiment.pk, [])+ if source.metric_uuid in session_hits+ }.values(),+ key=lambda hit: hit.first_timestamp,+ )+ items.append(+ ExperimentSessionContextItem(+ experiment_id=experiment.pk,+ experiment_name=experiment.name,+ flag_key=experiment.feature_flag.key,+ variant=variant,+ variants_seen=variants_seen,+ multiple_variants=len(variants_seen) > 1,+ first_exposure_timestamp=first_exposure_timestamp,+ experiment_start_date=experiment.start_date,+ experiment_end_date=experiment.end_date,+ metrics_in_session=metrics_in_session,+ )+ )+ results[session_id] = sorted(items, key=lambda item: item.experiment_name.lower())+ return results, capped_session_idsdef _resolve_exposure(flag_key: str, exposure_criteria: Optional[dict]) -> _ResolvedExposure:@@ -415,17 +689,18 @@ def _query_flag_evaluations(team: Team,user: User,shared_hogql: SharedHogQLDatabase,- session_id: str,+ session_ids: list[str],window_start: datetime,window_end: datetime,flag_keys: set[str],variants: set[str],-) -> dict[str, list[tuple[str, datetime]]]:- """The session's `$feature_flag_called` events for the given experiment flag keys and- defined variant names, as flag_key -> [(variant, first_seen)]. Serves two roles: variant- evidence for every experiment (the replay shows what the session was served, whatever the- exposure criteria say), and the exposure moment for experiments whose criteria resolve to- the plain default shape (`$feature_flag_called` with no extra property filters).+) -> dict[str, dict[str, list[tuple[str, datetime]]]]:+ """The sessions' `$feature_flag_called` events for the given experiment flag keys and+ defined variant names, as session_id -> flag_key -> [(variant, first_seen)]. Serves two+ roles: variant evidence for every experiment (the replay shows what the session was+ served, whatever the exposure criteria say), and the exposure moment for experiments whose+ criteria resolve to the plain default shape (`$feature_flag_called` with no extra property+ filters).Shape-bound to `$feature_flag_called` on purpose — the `$feature_flag` batching key andthe `$feature_flag_response` variant property come with that event, so all three are@@ -435,21 +710,22 @@ def _query_flag_evaluations(exposure moments move to the branch path."""query = parse_select("""- SELECT properties.$feature_flag AS flag_key,+ SELECT $session_id AS session_id,+ properties.$feature_flag AS flag_key,toString(properties.$feature_flag_response) AS variant,min(timestamp) AS first_seenFROM eventsWHERE event = '$feature_flag_called'- AND $session_id = {session_id}+ AND $session_id IN {session_ids}AND properties.$feature_flag IN {flag_keys}AND toString(properties.$feature_flag_response) IN {variants}AND timestamp >= {window_start}AND timestamp <= {window_end}- GROUP BY flag_key, variant+ GROUP BY session_id, flag_key, variantLIMIT {max_rows}""",placeholders={- "session_id": ast.Constant(value=session_id),+ "session_ids": ast.Constant(value=session_ids),"flag_keys": ast.Constant(value=sorted(flag_keys)),"variants": ast.Constant(value=sorted(variants)),"window_start": ast.Constant(value=window_start),@@ -461,11 +737,11 @@ def _query_flag_evaluations(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 []:+ exposures: dict[str, dict[str, list[tuple[str, datetime]]]] = {}+ for session_id, flag_key, variant, first_seen in response.results or []:if not flag_key or not variant:continue- exposures.setdefault(str(flag_key), []).append((str(variant), first_seen))+ exposures.setdefault(str(session_id), {}).setdefault(str(flag_key), []).append((str(variant), first_seen))return exposures@@ -473,14 +749,14 @@ def _query_exposure_event_branches(team: Team,user: User,shared_hogql: SharedHogQLDatabase,- session_id: str,+ session_ids: list[str],window_start: datetime,window_end: datetime,branch_meta: list[tuple[int, _ResolvedExposure, set[str]]],-) -> dict[int, list[tuple[str, datetime]]]:- """The session's exposure events for experiments whose criteria don't fit the batched+) -> dict[str, dict[int, list[tuple[str, datetime]]]]:+ """The sessions' exposure events for experiments whose criteria don't fit the batcheddefault query (a custom event, an action, or the default event narrowed by property- filters), as experiment_id -> [(variant, first_seen)].+ filters), as session_id -> experiment_id -> [(variant, first_seen)].One union branch per experiment: the event/action and property filters come from theexperiment's exposure criteria via `build_exposure_event_conditions`, and the variant from@@ -505,21 +781,22 @@ def _query_exposure_event_branches(branch = parse_select("""SELECT {experiment_id} AS experiment_id,+ $session_id AS session_id,toString({variant_field}) AS variant,min(timestamp) AS first_seenFROM eventsWHERE {exposure_conditions}- AND $session_id = {session_id}+ AND $session_id IN {session_ids}AND toString({variant_field}) IN {variants}AND timestamp >= {window_start}AND timestamp <= {window_end}- GROUP BY variant+ GROUP BY session_id, variant""",placeholders={"experiment_id": ast.Constant(value=experiment_id),"variant_field": ast.Field(chain=["properties", resolution.variant_property]),"exposure_conditions": ast.And(exprs=conditions) if conditions else ast.Constant(value=True),- "session_id": ast.Constant(value=session_id),+ "session_ids": ast.Constant(value=session_ids),"variants": ast.Constant(value=sorted(variants)),"window_start": ast.Constant(value=window_start),"window_end": ast.Constant(value=window_end),@@ -544,11 +821,11 @@ def _query_exposure_event_branches(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 []:+ exposures: dict[str, dict[int, list[tuple[str, datetime]]]] = {}+ for experiment_id, session_id, variant, first_seen in response.results or []:if not variant:continue- exposures.setdefault(int(experiment_id), []).append((str(variant), first_seen))+ exposures.setdefault(str(session_id), {}).setdefault(int(experiment_id), []).append((str(variant), first_seen))return exposures@@ -556,33 +833,38 @@ def _query_stamped_flag_properties(team: Team,user: User,shared_hogql: SharedHogQLDatabase,- session_id: str,+ session_ids: list[str],flag_keys: set[str],window_start: datetime,window_end: datetime,-) -> dict[str, list[str]]:- """Distinct stamped `$feature/<key>` property values in the session, as flag_key -> values."""+) -> dict[str, dict[str, list[str]]]:+ """Distinct stamped `$feature/<key>` property values per session, as+ session_id -> flag_key -> values. Sessions with no in-window events yield no entry."""sorted_keys = sorted(flag_keys)# Built as ast nodes, not string interpolation — flag keys can contain arbitrary characters.select: list[ast.Expr] = [- ast.Alias(- alias=f"v{index}",- expr=ast.Call(- name="groupUniqArray",- args=[ast.Call(name="toString", args=[ast.Field(chain=["properties", f"$feature/{key}"])])],- ),- )- for index, key in enumerate(sorted_keys)+ ast.Alias(alias="session_id", expr=ast.Field(chain=["$session_id"])),+ *[+ ast.Alias(+ alias=f"v{index}",+ expr=ast.Call(+ name="groupUniqArray",+ args=[ast.Call(name="toString", args=[ast.Field(chain=["properties", f"$feature/{key}"])])],+ ),+ )+ for index, key in enumerate(sorted_keys)+ ],]query = ast.SelectQuery(select=select,select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ group_by=[ast.Field(chain=["session_id"])],where=ast.And(exprs=[ast.CompareOperation(- op=ast.CompareOperationOp.Eq,+ op=ast.CompareOperationOp.In,left=ast.Field(chain=["$session_id"]),- right=ast.Constant(value=session_id),+ right=ast.Constant(value=session_ids),),ast.CompareOperation(op=ast.CompareOperationOp.GtEq,@@ -601,5 +883,7 @@ def _query_stamped_flag_properties(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)}+ return {+ str(row[0]): {key: [value for value in row[1 + index] if value] for index, key in enumerate(sorted_keys)}+ for row in response.results or []+ }diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.pyindex d4e0e9a83e1d..11689d1d7fdf 100644--- a/products/experiments/backend/test/test_metric_events.py+++ b/products/experiments/backend/test/test_metric_events.py@@ -16,7 +16,7 @@ from products.experiments.backend.metric_events import (MetricHit,MetricSourceRole,resolve_metric_events,- scan_session_for_metric_events,+ scan_sessions_for_metric_events,)from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -257,14 +257,14 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)def _scan(self, metrics: list[dict[str, Any]], session_id: str) -> list[MetricHit]:experiment = self._experiment(metrics=metrics)- return scan_session_for_metric_events(+ return scan_sessions_for_metric_events(self.team,self.user,metric_sources=resolve_metric_events(experiment),- session_id=session_id,+ session_ids=[session_id],window_start=WINDOW_START,window_end=WINDOW_END,- )+ ).hits_by_session.get(session_id, [])def test_reports_hits_only_for_metrics_with_in_window_events(self) -> None:# Two metrics with different sources prove the combined query aggregates each source@@ -357,6 +357,31 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)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_hits_are_attributed_per_session(self) -> None:+ # The batch endpoint scans several sessions in one grouped query; a hit landing on the+ # wrong session (or a session with no events getting a row) would show another+ # session's metrics in the player.+ metric = _metric("mean", name="Purchases", source=_events_node("purchase"))+ self._create_session_event("purchase", "s1", timestamp="2026-01-01T10:05:00Z")+ self._create_session_event("purchase", "s2", timestamp="2026-01-01T10:07:00Z")+ self._create_session_event("purchase", "s2", timestamp="2026-01-01T10:09:00Z")+ flush_persons_and_events()++ experiment = self._experiment(metrics=[metric])+ hits_by_session = scan_sessions_for_metric_events(+ self.team,+ self.user,+ metric_sources=resolve_metric_events(experiment),+ session_ids=["s1", "s2", "s3"],+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ ).hits_by_session++ assert set(hits_by_session) == {"s1", "s2"}+ assert hits_by_session["s1"][0].event_count == 1+ assert hits_by_session["s2"][0].event_count == 2+ assert hits_by_session["s2"][0].first_timestamp == datetime(2026, 1, 1, 10, 7, 0, tzinfo=UTC)+def test_hit_reports_which_sources_fired(self) -> None:# A funnel hit must say which step fired: without the breakdown, a session that only fired# the last step reads as "reached this metric", which is what the analysis would deny.@@ -548,7 +573,18 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)self._create_session_event("signup", "s1")flush_persons_and_events()+ experiment = self._experiment(metrics=[first, second, shared])with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):- hits = self._scan([first, second, shared], "s1")-- assert [hit.metric_uuid for hit in hits] == [first["uuid"]]+ result = scan_sessions_for_metric_events(+ self.team,+ self.user,+ metric_sources=resolve_metric_events(experiment),+ session_ids=["s1"],+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ )++ assert [hit.metric_uuid for hit in result.hits_by_session["s1"]] == [first["uuid"]]+ # The overflow must be reported, not just logged: session_context relies on it to keep+ # capped batch results out of the cache.+ assert result.dropped_metric_uuids == {second["uuid"], shared["uuid"]}diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 6a209d3af6d6..ff0b40da0298 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, Optionalfrom freezegun import freeze_time@@ -6,6 +6,7 @@ from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_from unittest.mock import patchfrom django.core.cache import cache+from django.test import SimpleTestCasefrom rest_framework import status@@ -16,12 +17,18 @@ from posthog.constants import AvailableFeaturefrom posthog.models import PropertyDefinition, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7+from posthog.rate_limit import SessionContextsBurstRateThrottlefrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.access_control.backend.facade.api import upsert_property_access_controlfrom products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInputfrom products.actions.backend.models.action import Actionfrom products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.experiments.backend.session_context import (+ MAX_SESSION_CONTEXT_BATCH,+ _bounded_metadata_ids,+ _query_stamped_flag_properties,+)from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTest@@ -30,6 +37,10 @@ from ee.models.rbac.access_control import AccessControlRECORDING_START = datetime(2026, 1, 1, 10, 0, 0, tzinfo=UTC)RECORDING_END = datetime(2026, 1, 1, 10, 30, 0, tzinfo=UTC)SESSION_ID = str(uuid7(unix_ms_time=int(RECORDING_START.timestamp() * 1000)))+# A second recording on a different day, so batch tests exercise the per-day chunking path.+DAY_TWO_RECORDING_START = datetime(2025, 12, 31, 10, 0, 0, tzinfo=UTC)+DAY_TWO_RECORDING_END = datetime(2025, 12, 31, 10, 30, 0, tzinfo=UTC)+DAY_TWO_SESSION_ID = str(uuid7(unix_ms_time=int(DAY_TWO_RECORDING_START.timestamp() * 1000)))def _hogql_table_tree(node: TableNode) -> dict[str, Any]:@@ -120,6 +131,27 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):params = {"session_id": session_id} if session_id is not None else {}return self.client.get(f"/api/projects/{self.team.id}/experiments/session_context/", params)+ def _post_session_contexts(self, session_ids: list[str]) -> Any:+ return self.client.post(+ f"/api/projects/{self.team.id}/experiments/session_contexts/",+ {"session_ids": session_ids},+ format="json",+ )++ def _create_day_two_recording_with_exposure(self, variant: str = "control") -> None:+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=DAY_TWO_SESSION_ID,+ distinct_id="user1",+ first_timestamp=DAY_TWO_RECORDING_START,+ last_timestamp=DAY_TWO_RECORDING_END,+ )+ self._create_session_event(+ timestamp="2025-12-31T10:03:00Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": variant},+ session_id=DAY_TWO_SESSION_ID,+ )+def test_requires_session_id(self) -> None:response = self._get_session_context(session_id=None)assert response.status_code == status.HTTP_400_BAD_REQUEST@@ -627,7 +659,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):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:+ with patch("products.experiments.backend.session_context._compute_session_experiment_contexts") as compute:second = self._get_session_context()compute.assert_not_called()assert second.json() == first.json()@@ -834,3 +866,394 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):response = self._get_session_context()assert response.status_code == status.HTTP_200_OKassert response.json()["results"] == []++ def test_batch_returns_same_items_as_single_calls(self) -> None:+ # Two sessions on different recording days force the day-chunked path, a custom-criteria+ # experiment forces the branch query, and a metric event in only one session forces+ # per-session metric attribution — all of which must produce exactly what N single+ # requests produce.+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "11111111-1111-1111-1111-111111111111",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ self._create_experiment(metrics=[metric])+ self._create_experiment(+ key="pricing-banner",+ name="Pricing banner",+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ },+ )+ self._create_recording()+ 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")+ self._create_session_event(+ event="checkout started",+ timestamp="2026-01-01T10:05:00Z",+ properties={"$feature/pricing-banner": "test"},+ )+ self._create_day_two_recording_with_exposure(variant="control")+ flush_persons_and_events()++ singles = {+ session_id: self._get_session_context(session_id).json() for session_id in (SESSION_ID, DAY_TWO_SESSION_ID)+ }+ cache.clear()++ # The duplicate id must collapse to one entry, in request order.+ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID, SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ entries = response.json()["results"]+ assert [entry["session_id"] for entry in entries] == [SESSION_ID, DAY_TWO_SESSION_ID]+ assert {entry["session_id"]: entry for entry in entries} == singles+ # Guard against "singles and batch are both wrong": pin the expected values too.+ day_one = {result["flag_key"]: result for result in entries[0]["results"]}+ assert day_one["checkout-cta"]["variant"] == "test"+ assert [hit["metric_uuid"] for hit in day_one["checkout-cta"]["metrics_in_session"]] == [metric["uuid"]]+ assert day_one["pricing-banner"]["first_exposure_timestamp"] == "2026-01-01T10:05:00Z"+ assert [+ (result["flag_key"], result["variant"], result["metrics_in_session"]) for result in entries[1]["results"]+ ] == [("checkout-cta", "control", [])]++ def test_batch_warms_cache_for_single_endpoint(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()++ batch = self._post_session_contexts([SESSION_ID])+ assert batch.status_code == status.HTTP_200_OK++ 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() == batch.json()["results"][0]++ def test_batch_written_cache_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()++ # Prefetch as the private experiment's creator, who sees both experiments.+ self.client.force_login(other_user)+ response = self._post_session_contexts([SESSION_ID])+ assert [result["flag_key"] for result in response.json()["results"][0]["results"]] == [+ "checkout-cta",+ "private-exp",+ ]++ # The batch-written entry must not leak the private experiment to another viewer.+ 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_batch_omits_missing_recordings_and_never_caches_them(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()++ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])+ assert response.status_code == status.HTTP_200_OK+ assert [entry["session_id"] for entry in response.json()["results"]] == [SESSION_ID]++ # The missing recording finishes ingesting; the next batch must compute it rather+ # than serve a cached "absent".+ self._create_day_two_recording_with_exposure(variant="control")+ flush_persons_and_events()++ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])+ 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 = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "22222222-2222-2222-2222-222222222222",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ extra_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",+ start_date=datetime(2025, 12, 15, tzinfo=UTC),+ metrics=[shared_metric],+ )+ self._create_experiment(key="extra-exp", name="Extra experiment", metrics=[extra_metric])++ self._create_recording()+ self._create_session_event(properties={"$feature_flag": "shared-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).+ second_session_id = str(uuid7(unix_ms_time=int((RECORDING_START + timedelta(minutes=40)).timestamp() * 1000)))+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=second_session_id,+ distinct_id="user1",+ first_timestamp=RECORDING_START + timedelta(minutes=40),+ last_timestamp=RECORDING_END + timedelta(minutes=40),+ )+ for event, timestamp, properties in (+ (+ "$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"},+ ),+ ("signup", "2026-01-01T10:43:00Z", {}),+ ):+ self._create_session_event(+ event=event, timestamp=timestamp, properties=properties, session_id=second_session_id+ )+ flush_persons_and_events()++ with 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_OK+ by_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"] == []++ # The unaffected session 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"]+ ]++ 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 —+ # stamped-only evidence is never rescued. The cap must apply per day-chunk.+ self._create_experiment(+ key="old-exp",+ name="Old experiment",+ start_date=datetime(2025, 12, 1, tzinfo=UTC),+ end_date=datetime(2025, 12, 31, 23, 0, tzinfo=UTC),+ )+ self._create_experiment(key="new-exp", name="New experiment", start_date=datetime(2026, 1, 1, tzinfo=UTC))+ self._create_recording()+ self._create_session_event(event="$pageview", properties={"$feature/new-exp": "test"})+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=DAY_TWO_SESSION_ID,+ distinct_id="user1",+ first_timestamp=DAY_TWO_RECORDING_START,+ last_timestamp=DAY_TWO_RECORDING_END,+ )+ self._create_session_event(+ event="$pageview",+ timestamp="2025-12-31T10:03:00Z",+ properties={"$feature/old-exp": "control"},+ session_id=DAY_TWO_SESSION_ID,+ )+ flush_persons_and_events()++ with patch("products.experiments.backend.session_context.MAX_CANDIDATE_EXPERIMENTS", 1):+ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ by_id = {entry["session_id"]: entry["results"] for entry in response.json()["results"]}+ assert [result["flag_key"] for result in by_id[SESSION_ID]] == ["new-exp"]+ assert [result["flag_key"] for result in by_id[DAY_TWO_SESSION_ID]] == ["old-exp"]++ def test_batch_caps_distinct_recording_days(self) -> None:+ # Ids scattered across many days would fan one throttled HTTP request out into a scan+ # set per day; only the most recent days within the budget are computed, and the rest+ # are omitted without being cached, so the single endpoint still computes them.+ self._create_recording()+ self._create_experiment()+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ self._create_day_two_recording_with_exposure()+ flush_persons_and_events()++ with patch("products.experiments.backend.session_context.MAX_SESSION_CONTEXT_BATCH_DAYS", 1):+ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ assert [entry["session_id"] for entry in response.json()["results"]] == [SESSION_ID]++ single = self._get_session_context(DAY_TWO_SESSION_ID)+ assert [result["variant"] for result in single.json()["results"]] == ["control"]++ def test_batch_rejects_invalid_session_id_lists(self) -> None:+ assert self._post_session_contexts([]).status_code == status.HTTP_400_BAD_REQUEST+ over_cap = [str(uuid7()) for _ in range(MAX_SESSION_CONTEXT_BATCH + 1)]+ assert self._post_session_contexts(over_cap).status_code == status.HTTP_400_BAD_REQUEST++ def test_batch_builds_hogql_database_once(self) -> None:+ # Two sessions on different days run as two day-chunks; the expensive HogQL database+ # build must still happen once for the whole batch, not once per chunk or per scan.+ self._create_recording()+ self._create_experiment()+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ self._create_day_two_recording_with_exposure()+ flush_persons_and_events()++ original_create_for = Database.create_for+ with patch.object(Database, "create_for", side_effect=original_create_for) as create_for:+ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()["results"]) == 2+ assert create_for.call_count == 1++ def test_batch_failing_chunk_omits_only_its_sessions(self) -> None:+ # The batch prefetch is best-effort: one chunk's scans blowing up must not fail the+ # request (or poison the cache) for the other sessions.+ self._create_recording()+ self._create_experiment()+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ self._create_day_two_recording_with_exposure()+ flush_persons_and_events()++ def _explode_for_day_two(team: Any, user: Any, shared_hogql: Any, session_ids: list[str], *args: Any) -> Any:+ if DAY_TWO_SESSION_ID in session_ids:+ raise ValueError("simulated scan failure")+ return _query_stamped_flag_properties(team, user, shared_hogql, session_ids, *args)++ with patch(+ "products.experiments.backend.session_context._query_stamped_flag_properties",+ side_effect=_explode_for_day_two,+ ):+ response = self._post_session_contexts([SESSION_ID, DAY_TWO_SESSION_ID])++ assert response.status_code == status.HTTP_200_OK+ assert [entry["session_id"] for entry in response.json()["results"]] == [SESSION_ID]++ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_batch_throttles_session_authenticated_users(self, _enabled: Any) -> None:+ # The ClickHouse* throttle pair only limits personal-API-key traffic; this endpoint's+ # primary caller is the session-authenticated web app, so swapping back to those+ # classes would leave the heavy batch compute unthrottled for its real traffic.+ self._create_recording()++ with patch.object(SessionContextsBurstRateThrottle, "rate", "2/minute"):+ assert self._post_session_contexts([SESSION_ID]).status_code == status.HTTP_200_OK+ assert self._post_session_contexts([SESSION_ID]).status_code == status.HTTP_200_OK+ throttled = self._post_session_contexts([SESSION_ID])++ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS++ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_batch_throttle_budget_is_shared_across_personal_api_keys(self, _enabled: Any) -> None:+ # The default throttle cache key idents personal-API-key requests by key hash, so a+ # user could mint keys to multiply the expensive batch compute; the budget must be one+ # project-wide bucket regardless of which key (or session) makes the request.+ self._create_recording()+ self.client.logout()++ def _post_with_new_key() -> Any:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="t",+ secure_value=hash_key_value(token),+ scopes=["experiment:read", "session_recording:read"],+ )+ return self.client.post(+ f"/api/projects/{self.team.id}/experiments/session_contexts/",+ {"session_ids": [SESSION_ID]},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )++ with patch.object(SessionContextsBurstRateThrottle, "rate", "2/minute"):+ assert _post_with_new_key().status_code == status.HTTP_200_OK+ assert _post_with_new_key().status_code == status.HTTP_200_OK+ throttled = _post_with_new_key()++ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS++ def test_batch_requires_session_recording_read_scope(self) -> None:+ self._create_recording()+ self.client.logout()++ def _personal_api_key(scopes: list[str]) -> str:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(user=self.user, label="t", secure_value=hash_key_value(token), scopes=scopes)+ return token++ token = _personal_api_key(["experiment:read"])+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/session_contexts/",+ {"session_ids": [SESSION_ID]},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ token = _personal_api_key(["experiment:read", "session_recording:read"])+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/session_contexts/",+ {"session_ids": [SESSION_ID]},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )+ assert response.status_code == status.HTTP_200_OK+++class TestBoundedMetadataIds(SimpleTestCase):+ def test_id_without_usable_bound_is_excluded_instead_of_unbounding_the_scan(self) -> None:+ # One legacy/garbage id in a batch must not remove the min_first_timestamp bound from+ # the whole metadata query — it gets dropped from the lookup, keeping the bound from+ # the ids that parse.+ bounded_ids, lower_bound = _bounded_metadata_ids([SESSION_ID, "legacy-session-id", DAY_TWO_SESSION_ID])++ assert bounded_ids == [SESSION_ID, DAY_TWO_SESSION_ID]+ assert lower_bound is not None+ assert lower_bound <= DAY_TWO_RECORDING_START++ def test_all_ids_without_bound_yield_empty_lookup(self) -> None:+ assert _bounded_metadata_ids(["legacy-a", "legacy-b"]) == ([], None)diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 71b2e6217ce3..83dc11e32eb8 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2341,6 +2341,26 @@ export interface ExperimentSessionContextResponseApi {results: ExperimentSessionContextItemApi[]}+/**+ * Request body for the batch session-context endpoint.+ */+export interface ExperimentSessionContextsRequestApi {+ /**+ * IDs of the session recordings to resolve experiment context for, at most 20 per request. Duplicates are ignored.+ * @minItems 1+ * @maxItems 20+ */+ session_ids: string[]+}++/**+ * Experiment/variant context for a batch of session recordings.+ */+export interface ExperimentSessionContextsResponseApi {+ /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */+ results: ExperimentSessionContextResponseApi[]+}+export type ExperimentHoldoutsListParams = {/*** Number of results to return per page.diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 16051a7d94f9..d0bee2c65adf 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -22,6 +22,8 @@ import type {ExperimentSavedMetricApi,ExperimentSavedMetricsListParams,ExperimentSessionContextResponseApi,+ ExperimentSessionContextsRequestApi,+ ExperimentSessionContextsResponseApi,ExperimentWriteApi,ExperimentsActivityRetrieveParams,ExperimentsListParams,@@ -1067,6 +1069,35 @@ export const experimentsSessionContextRetrieve = async (})}+export const getExperimentsSessionContextsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/experiments/session_contexts/`+}++/**+ * Resolve experiment context for a batch of session recordings.+ *+ * Batch variant of `session_context`, used to prefetch the replay player's experiments+ * box for a whole recordings list in one request. POST because the id list doesn't fit a+ * query string; the endpoint only reads. Already-computed sessions are served from (and+ * cold ones written to) the same short-lived per-viewer cache the single-session endpoint+ * uses, so opening any prefetched recording renders its context instantly. Sessions whose+ * recording metadata doesn't exist yet are omitted from the response, as are sessions+ * beyond the batch's recording-day budget (each distinct recording day costs its own set+ * of ClickHouse scans, so only the most recent days are computed per request).+ */+export const experimentsSessionContextsCreate = async (+ projectId: string,+ experimentSessionContextsRequestApi: ExperimentSessionContextsRequestApi,+ options?: RequestInit+): Promise<ExperimentSessionContextsResponseApi> => {+ return apiMutator<ExperimentSessionContextsResponseApi>(getExperimentsSessionContextsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(experimentSessionContextsRequestApi),+ })+}+export const getExperimentsStatsRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/experiments/stats/`}diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex 28fc16bd8227..35701649f8b3 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -1243,3 +1243,29 @@ export const ExperimentsCreateFromPromptCreateBody = /* @__PURE__ */ zod.object(.describe('Optional feature flag key. If omitted, a slug is derived from the experiment name.'),description: zod.string().optional().describe('Optional experiment description.'),})++/**+ * Resolve experiment context for a batch of session recordings.+ *+ * Batch variant of `session_context`, used to prefetch the replay player's experiments+ * box for a whole recordings list in one request. POST because the id list doesn't fit a+ * query string; the endpoint only reads. Already-computed sessions are served from (and+ * cold ones written to) the same short-lived per-viewer cache the single-session endpoint+ * uses, so opening any prefetched recording renders its context instantly. Sessions whose+ * recording metadata doesn't exist yet are omitted from the response, as are sessions+ * beyond the batch's recording-day budget (each distinct recording day costs its own set+ * of ClickHouse scans, so only the most recent days are computed per request).+ */+export const experimentsSessionContextsCreateBodySessionIdsMax = 20++export const ExperimentsSessionContextsCreateBody = /* @__PURE__ */ zod+ .object({+ session_ids: zod+ .array(zod.string().describe('ID of one session recording.'))+ .min(1)+ .max(experimentsSessionContextsCreateBodySessionIdsMax)+ .describe(+ 'IDs of the session recordings to resolve experiment context for, at most 20 per request. Duplicates are ignored.'+ ),+ })+ .describe('Request body for the batch session-context endpoint.')diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex e34f93782f99..711463c3bd46 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -1266,6 +1266,9 @@ tools:experiments-session-context-retrieve:operation: experiments_session_context_retrieveenabled: false+ experiments-session-contexts-create:+ operation: experiments_session_contexts_create+ enabled: falseexperiments-update:operation: experiments_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0bc608c81aa2..4e37d7b37047 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27908,6 +27908,26 @@ export namespace Schemas {results: ExperimentSessionContextItem[];}+ /**+ * Request body for the batch session-context endpoint.+ */+ export interface ExperimentSessionContextsRequest {+ /**+ * IDs of the session recordings to resolve experiment context for, at most 20 per request. Duplicates are ignored.+ * @minItems 1+ * @maxItems 20+ */+ session_ids: string[];+ }++ /**+ * Experiment/variant context for a batch of session recordings.+ */+ export interface ExperimentSessionContextsResponse {+ /** Per-session experiment context, in the order the session IDs were requested. Sessions whose recording metadata doesn't exist yet (still ingesting, or unknown to this project) are omitted, as are sessions beyond the batch's recording-day budget (only the most recent days are computed). Fetch omitted sessions individually via the single-session endpoint. */+ results: ExperimentSessionContextResponse[];+ }+/*** Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.*/