Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(experiments): anchor recordings metric filter to the latest exposure (#98912)

Marcel Poelkerb37180e368c9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index afb66f9ae203..c5afc8bf2834 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7385,13 +7385,13 @@ snapshots:
scenes-app-experiments--experiment-recordings-empty-in-session-has-none--light:
hash: v1.k794b7964.17ae28c96ffb6e5f325c1d6472a3d0daf74ebc5f587e71c6e1e519c3ae90cfde.gxIuB-JGrgOu019Z-fO3qd5xJdDjYnakTZFb8ifWRd4
scenes-app-experiments--experiment-recordings-empty-metric-filter-failed--dark:
- hash: v1.k794b7964.5bcdedce15abcde17d42fb48cbb10113bcb4a5d13b1fc77b33004f4489bb28f7.RErYd5Fhw_0HL83KG4-o2P3E0010HXhf7zGyTjPysyE
+ hash: v1.k794b7964.de0dcdbb378afe30e253b77bf6f65f0951ade1d64f1130b0f434d84b860aae75.XeFu9_MgfbNR9OcHkHT1GfxXwqLVh5l1sZdIMUyCDwU
scenes-app-experiments--experiment-recordings-empty-metric-filter-failed--light:
- hash: v1.k794b7964.122650d92376c8deb66d05818fd951ee6c3ef9547e36cc4cb90319283d4e5b91.UPiCTjRgAuc_xzEnxre4KeFY-7Gi2z8M-LGfZBztRzQ
+ hash: v1.k794b7964.4b69ebc9a53ee1741178c1594b08d25d3eb43fa5a834db4c6299d009b62c4953.HF9LK-eTwE5qJzSb23ClXWYy-gXrOQohPVPC6zS2uJ0
scenes-app-experiments--experiment-recordings-empty-metric-filter-matched-nothing--dark:
- hash: v1.k794b7964.2abb549c5ccab18a46aaba2c29495c1522cec73f66f19dd9ede59e08ba7b0472.m8YY2HCJZBIPbrKEy7LIJKaG07qR_AjZATroyJPg7x0
+ hash: v1.k794b7964.7501d0ad4714cc8f2fb695e0b521711d71782ef89f65f214f0caa59bd823d331.rE7WfJJeJxDyWv4g_1KTSck6M8mbXISvSdqO4XuDd_k
scenes-app-experiments--experiment-recordings-empty-metric-filter-matched-nothing--light:
- hash: v1.k794b7964.1fc5dafbe824292161867932af884a6a9065e4e6876e8a02d2bc70f8f9f94288.q5oxrAyeYGEoeVe2d-8KK0UlyQwJdPaieJP6vSnAGd4
+ hash: v1.k794b7964.c3d237d41b22bc16d68bf8bca2baf3fb2b680130fa285095c0a6c030e3c85832.9_we98SUgw_Q58Ew7VB7ZYmfk1qNxr5KH5HSmcmhAq0
scenes-app-experiments--experiment-recordings-empty-too-early--dark:
hash: v1.k794b7964.461cc90ab6b2e52b99111e0631d253e47347647f994b2500ceb87eeb77c6b771.3taB8yr84NutLTUwM3FMvtp-Z9R0KSmjXY1j9hUx5R0
scenes-app-experiments--experiment-recordings-empty-too-early--light:
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.test.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.test.tsx
index 05756d258362..00e4978f069a 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.test.tsx
@@ -17,6 +17,7 @@ import {
import { teamLogic } from 'scenes/teamLogic'
import { useMocks } from '~/mocks/jest'
+import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { Experiment, FilterLogicalOperator, TeamType } from '~/types'
@@ -55,7 +56,17 @@ const EXPERIMENT = {
feature_flag_key: 'my-flag',
start_date: daysAgo(10),
end_date: null,
- metrics: [],
+ // The metric-filter reasons need a metric to tick: no mode narrows the list on an empty
+ // selection, so without one the filter never asks the endpoint anything.
+ metrics: [
+ {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ uuid: 'metric-purchase',
+ name: 'Purchase',
+ source: { kind: NodeKind.EventsNode, event: 'purchase' },
+ },
+ ],
metrics_secondary: [],
feature_flag: {
filters: {
@@ -137,17 +148,41 @@ const REASON_CASES: ReasonCase[] = [
excluded_metrics: [],
filter_test_accounts: true,
})
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
},
copy: 'No recordings matched the metric filter.',
actions: [],
},
+ {
+ // A running experiment whose exposures stopped, so the filter's window sits behind
+ // retention. Naming the run's end here would print no date at all.
+ reason: ExperimentReplayListEmptyReason.EndedPastRetention,
+ experimentId: 214,
+ experiment: { start_date: daysAgo(120), end_date: null },
+ setup: (logic) => {
+ ;(experimentsSessionBucketsCreate as jest.Mock).mockResolvedValue({
+ session_ids: [],
+ truncated: false,
+ considered_metrics: [],
+ excluded_metrics: [],
+ date_from: daysAgo(90),
+ date_to: daysAgo(60),
+ filter_test_accounts: true,
+ })
+ logic.actions.setMetricSelected('metric-purchase', true)
+ logic.actions.setMetricFilterMode('no_metric_activity')
+ },
+ copy: 'This filter only covers sessions up to',
+ actions: ['experiment-recordings-empty-retention-docs'],
+ },
{
reason: ExperimentReplayListEmptyReason.MetricFilterFailed,
experimentId: 206,
experiment: { start_date: daysAgo(10), end_date: null },
setup: (logic) => {
;(experimentsSessionBucketsCreate as jest.Mock).mockRejectedValue({ detail: 'refused' })
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
},
copy: 'The metric filter could not be loaded',
@@ -281,6 +316,7 @@ describe('ExperimentRecordingsListEmptyState', () => {
experiment: { ...EXPERIMENT, id: 213 } as Experiment,
})
logic.mount()
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
await waitFor(() => expect(logic.values.sessionBucketLoading).toBe(true))
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.tsx
index 9e683b1dc830..21d0b9ae862b 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentRecordingsListEmptyState.tsx
@@ -82,9 +82,11 @@ function ReasonBanner({
'data-attr': 'experiment-recordings-empty-retention-docs',
}}
>
- This experiment ended on {dayjs(context.endDate).format('MMM D, YYYY')}. This project keeps recordings
- for {pluralize(context.retentionWindowDays, 'day')}, so the recordings from its run are no longer
- stored.
+ {context.scannedWindowEnd
+ ? `This filter only covers sessions up to ${dayjs(context.scannedWindowEnd).format('MMM D, YYYY')}.`
+ : `This experiment ended on ${dayjs(context.endDate).format('MMM D, YYYY')}.`}{' '}
+ This project keeps recordings for {pluralize(context.retentionWindowDays, 'day')}, so those recordings
+ are no longer stored.
</LemonBanner>
)
}
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index 39ea65712010..f16b7e13445d 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -15,6 +15,7 @@ import {
DropdownMenuTrigger,
} from '@posthog/quill'
+import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link'
@@ -116,7 +117,7 @@ function metricFilterTriggerLabel(
if (selectedUuids.length === 0) {
// Never fall back to the neutral label for a non-default mode: the mode is on, and the
// caption below is what explains why it isn't narrowing anything yet.
- return mode === 'fired_all' ? 'Metric events' : mode === 'fired_any' ? 'Fired any' : 'No metric events'
+ return mode === 'fired_all' ? 'Metric events' : mode === 'fired_any' ? 'Fired any' : 'Fired none'
}
const metrics = pluralize(selectedUuids.length, 'metric')
if (selectedUuids.length === 1) {
@@ -142,13 +143,23 @@ function unappliedModeReason(mode: ExperimentReplayMetricFilterMode): string {
/**
* States what the server-computed set does and doesn't cover. Every clause is load-bearing: the
- * list is capped, the scan window is clamped, and "in this session" is the honest unit — the
- * experiment analysis counts per person over the whole run window.
+ * list is capped, the scan window ends at the last exposure and reaches back only so far from
+ * there, and "in this session" is the honest unit — the experiment analysis counts per person over
+ * the whole run window.
*/
-function bucketCaption(bucket: ExperimentSessionBucket): string {
- const { session_ids, truncated, considered_metrics, excluded_metrics, filter_test_accounts } = bucket.response
+function bucketCaption(bucket: ExperimentSessionBucket, experimentStartDate: string | null): string {
+ const { session_ids, truncated, considered_metrics, excluded_metrics, filter_test_accounts, date_from, date_to } =
+ bucket.response
+ // The backend clamps the window start to the experiment's start, so a scan that reached the
+ // whole run comes back with the two equal and leaves this null.
+ const scannedFrom =
+ date_from && experimentStartDate && dayjs(date_from).isAfter(dayjs(experimentStartDate))
+ ? dayjs(date_from).format('MMM D, YYYY')
+ : null
if (session_ids.length === 0) {
- return 'No recordings matched this filter.'
+ return scannedFrom
+ ? `No recordings matched this filter between ${scannedFrom} and ${dayjs(date_to).format('MMM D, YYYY')}. Earlier sessions weren't checked.`
+ : 'No recordings matched this filter.'
}
const sessions = truncated
? `Showing the ${session_ids.length} most recent recordings that`
@@ -168,7 +179,8 @@ function bucketCaption(bucket: ExperimentSessionBucket): string {
.join(', ')}`
: null,
].filter(Boolean)
- return `${sessions} ${what}.${caveats.length > 0 ? ` ${caveats.join('. ')}.` : ''}`
+ const scanNote = scannedFrom ? ` Sessions before ${scannedFrom} weren't checked.` : ''
+ return `${sessions} ${what}.${caveats.length > 0 ? ` ${caveats.join('. ')}.` : ''}${scanNote}`
}
/** A metric row: its name, plus the events a session actually has to have fired to match it. */
@@ -197,8 +209,7 @@ const METRIC_FILTER_MODE_OPTIONS: { value: ExperimentReplayMetricFilterMode; lab
{
value: 'no_metric_activity',
label: 'Fired none',
- tooltip:
- 'Sessions that fired no events for any of the selected metrics. Select nothing to use every metric that can be matched.',
+ tooltip: 'Sessions that fired no events for any of the selected metrics.',
},
{
value: 'funnel_dropoff',
@@ -498,7 +509,9 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
) : sessionBucketLoading || !sessionBucket ? (
<span>Finding matching sessions…</span>
) : (
- <span data-attr="experiment-recordings-bucket-caption">{bucketCaption(sessionBucket)}</span>
+ <span data-attr="experiment-recordings-bucket-caption">
+ {bucketCaption(sessionBucket, experiment.start_date ?? null)}
+ </span>
)}
</div>
<ExperimentBehaviorComparison experiment={experiment} onWatchRecording={watchRecording} />
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index fa1b7f17d9c1..5ea57a2d54aa 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -58,8 +58,12 @@ const BUCKET_RESPONSE = {
truncated: false,
considered_metrics: [{ metric_uuid: 'metric-purchase', metric_name: 'Purchase' }],
excluded_metrics: [],
- date_from: '2026-01-01T00:00:00Z',
- date_to: '2026-02-01T00:00:00Z',
+ // Read against today, like the run windows below. A fixed scan window would age past the
+ // project's retention and start naming a different empty reason.
+ date_from: dayjs()
+ .subtract(30 * 24, 'hour')
+ .toISOString(),
+ date_to: dayjs().toISOString(),
filter_test_accounts: true,
}
@@ -207,6 +211,7 @@ const EMPTY_REASON_CASES: EmptyReasonCase[] = [
experiment: { start_date: daysAgo(10), end_date: null },
setup: (logic) => {
;(experimentsSessionBucketsCreate as jest.Mock).mockResolvedValue({ ...BUCKET_RESPONSE, session_ids: [] })
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
},
},
@@ -220,6 +225,23 @@ const EMPTY_REASON_CASES: EmptyReasonCase[] = [
...BUCKET_RESPONSE,
session_ids: ['bucket-session'],
})
+ logic.actions.setMetricSelected('metric-purchase', true)
+ logic.actions.setMetricFilterMode('no_metric_activity')
+ },
+ },
+ {
+ // A running experiment whose exposures stopped. The filter's window is anchored back
+ // there, so retention explains the empty list and changing the filter cannot.
+ reason: ExperimentReplayListEmptyReason.EndedPastRetention,
+ experimentId: 148,
+ experiment: { start_date: daysAgo(120), end_date: null },
+ setup: (logic) => {
+ ;(experimentsSessionBucketsCreate as jest.Mock).mockResolvedValue({
+ ...BUCKET_RESPONSE,
+ session_ids: [],
+ date_to: daysAgo(60),
+ })
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
},
},
@@ -991,6 +1013,7 @@ describe('experimentReplayTabLogic', () => {
experiment: { ...EXPERIMENT, id: 113, start_date: daysAgo(10), end_date: null } as Experiment,
})
failing.mount()
+ failing.actions.setMetricSelected('metric-purchase', true)
failing.actions.setMetricFilterMode('no_metric_activity')
// While the request is out the list is empty because the filter hasn't answered yet, and
@@ -1096,8 +1119,25 @@ describe('experimentReplayTabLogic', () => {
expect(recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
})
+ it.each(['fired_any', 'no_metric_activity', 'funnel_dropoff'] as const)(
+ 'leaves the list untouched when %s has no metric to apply',
+ async (mode) => {
+ await expectLogic(logic).toFinishAllListeners()
+ const before = logic.values.recordingsFilters
+
+ await expectLogic(logic, () => logic.actions.setMetricFilterMode(mode)).toFinishAllListeners()
+
+ // The shared playlist refetches on any deep change to its filters, so a mode with
+ // nothing ticked has to leave them alone. Otherwise picking the mode reloads the list
+ // and answers a question the unticked checkboxes never asked.
+ expect(logic.values.recordingsFilters).toEqual(before)
+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()
+ }
+ )
+
it('follows the playlist\'s own "Show all" back to the unbucketed list', async () => {
await expectLogic(logic, () => {
+ logic.actions.setMetricSelected('metric-purchase', true)
logic.actions.setMetricFilterMode('no_metric_activity')
}).toFinishAllListeners()
expect(logic.values.recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index c0e0118f740d..a337f1d9f437 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -183,6 +183,8 @@ export interface ExperimentRecordingsListEmptyContext {
retentionWindowDays: number
/** Null when the list holds every variant. */
variantKey: string | null
+ /** End of the window the applied metric filter scanned. Null when no filter is applied. */
+ scannedWindowEnd: string | null
}
/**
@@ -320,6 +322,7 @@ export interface experimentReplayTabLogicValues {
playlistFilters: RecordingUniversalFilters | null
playlistHeldForChecks: boolean
recordingsFilters: RecordingUniversalFilters
+ scannedWindowEnd: string | null
selectedMetricUuids: string[]
selectedVariantKey: string | null
selectedWatchCard: ExperimentWatchCardApi | null
@@ -612,6 +615,10 @@ export interface experimentReplayTabLogicMeta {
playlistFilters: RecordingUniversalFilters | null,
recordingsFilters: RecordingUniversalFilters
) => boolean
+ scannedWindowEnd: (
+ bucketSessionIds: string[] | undefined,
+ sessionBucket: ExperimentSessionBucket | null
+ ) => string | null
listEmptyReason: (
currentTeam: TeamPublicType | TeamType | null,
bucketSessionIds: string[] | undefined,
@@ -620,11 +627,13 @@ export interface experimentReplayTabLogicMeta {
recordingsFilters: RecordingUniversalFilters,
effectiveVariantKey: string | null,
effectiveExposureScope: ExperimentReplayExposureScope,
+ scannedWindowEnd: string | null,
arg: any
) => ExperimentReplayListEmptyReason
listEmptyContext: (
currentTeam: TeamPublicType | TeamType | null,
effectiveVariantKey: string | null,
+ scannedWindowEnd: string | null,
arg: any
) => ExperimentRecordingsListEmptyContext
filterContext: (
@@ -1152,6 +1161,16 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
(playlistFilters.date_to ?? null) !== (recordingsFilters.date_to ?? null) ||
!!playlistFilters.filter_test_accounts !== !!recordingsFilters.filter_test_accounts),
],
+ /**
+ * The end of the window the applied metric filter scanned, and null when no filter narrows
+ * the list. The endpoint anchors that window on the last exposure captured in a session, so
+ * on an experiment whose exposures stopped it sits well behind the end of the run.
+ */
+ scannedWindowEnd: [
+ (s) => [s.bucketSessionIds, s.sessionBucket],
+ (bucketSessionIds: string[] | undefined, sessionBucket: ExperimentSessionBucket | null): string | null =>
+ bucketSessionIds !== undefined ? (sessionBucket?.response.date_to ?? null) : null,
+ ],
/**
* The cause to name when the list comes back with nothing, first match wins. The order is
* cheapest-and-most-certain first: a project with replay off can have no recordings at all,
@@ -1170,6 +1189,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
s.recordingsFilters,
s.effectiveVariantKey,
s.effectiveExposureScope,
+ s.scannedWindowEnd,
(_, props) => props.experiment,
],
(
@@ -1180,6 +1200,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
recordingsFilters: RecordingUniversalFilters,
effectiveVariantKey: string | null,
effectiveExposureScope: ExperimentReplayExposureScope,
+ scannedWindowEnd: string | null,
experiment: Experiment
): ExperimentReplayListEmptyReason => {
if (!currentTeam?.session_recording_opt_in) {
@@ -1192,17 +1213,21 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
// nothing, because it must never widen the list back out. Told apart here rather
// than left to a join against `experiment recordings bucket failed`, so a broken
// endpoint can't inflate the count of filters that legitimately match nothing.
- if (bucketSessionIds?.length === 0) {
- return sessionBucketError !== null
- ? ExperimentReplayListEmptyReason.MetricFilterFailed
- : ExperimentReplayListEmptyReason.MetricFilterMatchedNothing
+ if (bucketSessionIds?.length === 0 && sessionBucketError !== null) {
+ return ExperimentReplayListEmptyReason.MetricFilterFailed
}
const retention = retentionDays(currentTeam.session_recording_retention_period)
const daysSinceStart = dayjs().diff(dayjs(experiment.start_date), 'day')
- const daysSinceEnd = daysSince(experiment.end_date)
- if (daysSinceEnd !== null && daysSinceEnd > retention) {
+ // Read against the window the list covers rather than the run: a metric filter
+ // stops at the last in-session exposure, so on an experiment whose exposures
+ // stopped every session it finds can predate retention, which no filter can fix.
+ const daysSinceWindowEnd = daysSince(scannedWindowEnd ?? experiment.end_date)
+ if (daysSinceWindowEnd !== null && daysSinceWindowEnd > retention) {
return ExperimentReplayListEmptyReason.EndedPastRetention
}
+ if (bucketSessionIds?.length === 0) {
+ return ExperimentReplayListEmptyReason.MetricFilterMatchedNothing
+ }
if (daysSinceStart < TOO_EARLY_DAYS) {
return ExperimentReplayListEmptyReason.TooEarly
}
@@ -1228,16 +1253,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
},
],
listEmptyContext: [
- (s) => [s.currentTeam, s.effectiveVariantKey, (_, props) => props.experiment],
+ (s) => [s.currentTeam, s.effectiveVariantKey, s.scannedWindowEnd, (_, props) => props.experiment],
(
currentTeam: TeamPublicType | TeamType | null,
effectiveVariantKey: string | null,
+ scannedWindowEnd: string | null,
experiment: Experiment
): ExperimentRecordingsListEmptyContext => ({
daysSinceStart: daysSince(experiment.start_date),
endDate: experiment.end_date ?? null,
retentionWindowDays: retentionDays(currentTeam?.session_recording_retention_period),
variantKey: effectiveVariantKey,
+ scannedWindowEnd,
}),
],
// What the list was narrowed by, shared by the opened-recording and list-rendered reports so
@@ -1374,9 +1401,9 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
},
],
/**
- * Null whenever the client-side event filters express the question exactly, so the list
- * keeps its uncapped path: no metric selected, and any "fired all" of several metrics
- * (ANDing filters is the one thing a recordings query can do).
+ * Null whenever the tab has no server-side set to ask for, so the list keeps its uncapped
+ * path: no metric selected in any mode, and any "fired all" of several metrics (ANDing
+ * filters is the one thing a recordings query can do).
*
* One selected metric is the interesting case. "Fired all of it" and "fired any of it"
* are the same question, so both take the same path — the client filter when the metric
@@ -1400,14 +1427,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
if (metricFilterMode === 'funnel_dropoff') {
return effectiveMetricUuids.length === 1 ? request('funnel_dropoff') : null
}
- if (metricFilterMode === 'no_metric_activity') {
- // Absence without a selection legitimately means every matchable metric.
- return request('no_metric_activity')
- }
if (effectiveMetricUuids.length === 0) {
- // "Fired any of nothing" has no answer.
+ // No mode narrows the list on an empty selection. The endpoint does read an
+ // empty metric list as "every matchable metric", but the checkboxes stay
+ // unticked while it does, so the list would answer a question the menu never
+ // shows.
return null
}
+ if (metricFilterMode === 'no_metric_activity') {
+ // Absence is the one question a recordings query can't express at all, however
+ // few events the selected metrics count.
+ return request('no_metric_activity')
+ }
if (effectiveMetricUuids.length > 1) {
return metricFilterMode === 'fired_any' ? request('fired_any') : null
}
diff --git a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx
index c34dec1ebde6..d32cdf9fba13 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx
@@ -80,9 +80,9 @@ export const ExperimentRecordingsEmptyEndedPastRetention: Story = {
* leaves testing-library's test id attribute at its default, unlike jest and Playwright, so a
* `data-attr` has to be matched as a plain attribute.
*/
-async function clickWhenRendered(canvasElement: HTMLElement, dataAttr: string): Promise<void> {
+async function clickWhenRendered(root: ParentNode, dataAttr: string): Promise<void> {
const control = await waitFor(() => {
- const button = canvasElement.querySelector<HTMLElement>(`[data-attr="${dataAttr}"]`)
+ const button = root.querySelector<HTMLElement>(`[data-attr="${dataAttr}"]`)
if (!button) {
throw new Error(`${dataAttr} not yet rendered`)
}
@@ -125,6 +125,9 @@ const pickFiredNone: Story['play'] = async ({ canvasElement }) => {
await clickWhenRendered(canvasElement, 'experiment-recordings-metric-filter')
// The menu content is a portal outside the canvas, so this searches the whole document.
await userEvent.click(await screen.findByText('Fired none'))
+ // No mode narrows the list until a metric is ticked, so without this the two stories stop
+ // reaching their empty states.
+ await clickWhenRendered(document, 'experiment-recordings-metric-option')
}
export const ExperimentRecordingsEmptyMetricFilterMatchedNothing: Story = {
@@ -136,6 +139,10 @@ export const ExperimentRecordingsEmptyMetricFilterMatchedNothing: Story = {
truncated: false,
considered_metrics: [{ metric_uuid: 'funnel', metric_name: 'Checkout funnel' }],
excluded_metrics: [],
+ // Later than the experiment's start, so the caption states the stretch of the
+ // run the scan left out.
+ date_from: '2025-05-25T00:00:00Z',
+ date_to: '2025-06-01T00:00:00Z',
filter_test_accounts: true,
},
},
diff --git a/posthog/session_recordings/data_retention.py b/posthog/session_recordings/data_retention.py
index b7582f178a1d..b4a8f1e6e735 100644
--- a/posthog/session_recordings/data_retention.py
+++ b/posthog/session_recordings/data_retention.py
@@ -1,6 +1,16 @@
from posthog.models.organization import ProductFeature
VALID_RETENTION_PERIODS = ["30d", "90d", "1y", "5y"]
+RETENTION_PERIOD_DAYS = {"30d": 30, "90d": 90, "1y": 365, "5y": 365 * 5}
+
+
+def retention_period_in_days(retention_period: str | None) -> int:
+ """How long this project keeps a recording, in days.
+
+ An unset or unrecognized period reads as the shortest the product offers, so a caller sizing a
+ scan by it reads too little rather than too much.
+ """
+ return RETENTION_PERIOD_DAYS.get(retention_period or "", RETENTION_PERIOD_DAYS["30d"])
def parse_feature_to_entitlement(retention_feature: ProductFeature | None) -> str | None:
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 2aea61d1057e..8fa78960da36 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1872,12 +1872,19 @@ class ExperimentSessionBucketResponseSerializer(serializers.Serializer):
)
date_from = serializers.DateTimeField(
help_text=(
- f"Start of the window scanned: the experiment's run window, clamped to its most recent "
- f"{MAX_BUCKET_SCAN_DAYS} days. Matches outside it are not returned."
+ f"Start of the window scanned, never before the experiment started. At most {MAX_BUCKET_SCAN_DAYS} days "
+ "before date_to when the scan found an exposure to anchor on. When it found none, how far back the "
+ "search for one reached, which the project's recording retention bounds. Matches outside the window "
+ "are not returned."
)
)
date_to = serializers.DateTimeField(
- help_text="End of the window scanned: the experiment's end date, or now while it runs."
+ help_text=(
+ "End of the window scanned: 24 hours after the latest exposure captured in a session, capped at the "
+ "experiment's end date or now. The pad covers the metric events a session fires after its exposure. "
+ "The scan ends at the experiment's end date, or now while it runs, when that exposure can't be "
+ "located, so an experiment whose exposures stopped long ago is still scanned where its sessions are."
+ )
)
filter_test_accounts = serializers.BooleanField(
help_text=(
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index f6a9f2ba609a..2d0ae7c3dadf 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -227,7 +227,7 @@ def _precomputation_covers_full_window(config: TeamExperimentsConfig, experiment
)
-def _fallback_evidence_scan_is_unaffordable(team: Team, experiment: Experiment) -> bool:
+def fallback_evidence_scan_is_unaffordable(team: Team, experiment: Experiment) -> bool:
"""Whether the stamped-property evidence scan must be refused for this team and experiment.
Unlike the exposure-event scan, the fallback has no event name to prune on, so it reads every
@@ -264,7 +264,7 @@ def resolve_in_session_exposure_semantics(team: Team, experiment: Experiment) ->
return InSessionExposureSemantics(
session_exposure=None, unavailable_reason=IN_SESSION_EXPOSURE_UNMATCHABLE_REASON
)
- if session_exposure.used_fallback and _fallback_evidence_scan_is_unaffordable(team, experiment):
+ if session_exposure.used_fallback and fallback_evidence_scan_is_unaffordable(team, experiment):
return InSessionExposureSemantics(
session_exposure=None, unavailable_reason=IN_SESSION_EXPOSURE_FALLBACK_TOO_LARGE_REASON
)
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index 9974a53eea40..aad8afbf6f16 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -61,6 +61,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.session_recordings.data_retention import retention_period_in_days
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.utils import get_safe_cache, safe_cache_set
@@ -81,7 +82,12 @@ from products.experiments.backend.metric_events import (
resolve_metric_events,
)
from products.experiments.backend.models.experiment import Experiment
-from products.experiments.backend.session_exposure import SessionExposure, resolve_session_exposure
+from products.experiments.backend.replay_linkage import fallback_evidence_scan_is_unaffordable
+from products.experiments.backend.session_exposure import (
+ MAX_SESSION_DURATION_HOURS,
+ SessionExposure,
+ resolve_session_exposure,
+)
logger = logging.getLogger(__name__)
@@ -90,9 +96,15 @@ logger = logging.getLogger(__name__)
# request-line limits proxies commonly enforce. Doubling it would not.
MAX_SESSION_BUCKET_LIMIT = 100
# The scan reads every session in the window, not a known id list, so the window is what bounds
-# it. Recency-ordered output capped at 100 means older sessions could not surface anyway, which
-# makes this clamp close to free in practice — but it must be stated wherever the bucket is.
+# it. It ends at the latest in-session exposure rather than at now, because an experiment whose
+# exposures stopped has nothing left in its recent days. The response carries the window it read,
+# because a clamped scan has to state what it left out.
MAX_BUCKET_SCAN_DAYS = 30
+# How far back the anchor looks for the latest exposure, before the project's replay retention
+# bounds it further. The scan prunes on the exposure event name, but that event is among the
+# highest-volume a team has and a run has no length cap, so an unbounded lookup on a long-stopped
+# experiment would read years of it on every cold request.
+MAX_ANCHOR_LOOKBACK_DAYS = 90
# Rows fetched before filtering to sessions that actually have a recording, so the cap isn't
# spent on sessions sampled out of replay.
RECORDING_LOOKUP_FACTOR = 3
@@ -254,8 +266,7 @@ def get_experiment_session_bucket(
if variant is not None and variant not in variant_keys:
raise SessionBucketUnavailable(f"'{variant}' is not a variant of this experiment.")
- window_end = experiment.end_date or timezone.now()
- window_start = max(experiment.start_date, window_end - timedelta(days=MAX_BUCKET_SCAN_DAYS))
+ run_end = experiment.end_date or timezone.now()
criteria = normalize_to_exposure_criteria(experiment.exposure_criteria)
filter_test_accounts = bool(criteria.filterTestAccounts) if criteria else False
limit = min(limit, MAX_SESSION_BUCKET_LIMIT)
@@ -286,8 +297,8 @@ def get_experiment_session_bucket(
bucket,
considered,
variant,
- window_start,
- window_end,
+ experiment.start_date,
+ run_end,
limit,
exposure.default_exposure_event,
)
@@ -295,18 +306,50 @@ def get_experiment_session_bucket(
if cached is not None:
return cached
- candidate_session_ids, scan_hit_cap = _query_bucket_sessions(
+ # Shared by both scans below, which read only `events` — the condition its docstring sets.
+ modifiers = create_default_modifiers_for_team(team)
+ shared_hogql = SharedHogQLDatabase(
+ # Postgres foreign-key lazy joins are the most expensive part of building the virtual
+ # database and these queries only read events.
+ database=Database.create_for(team=team, user=user, modifiers=modifiers, build_postgres_foreign_keys=False),
+ modifiers=modifiers,
+ )
+ scan_variant_keys = [variant] if variant is not None else sorted(variant_keys)
+ anchor_floor = _anchor_floor(team, run_start=experiment.start_date, run_end=run_end)
+ anchored_end = _resolve_window_end(
team,
user,
experiment,
- bucket=bucket,
- considered=considered,
- variant_keys=[variant] if variant is not None else sorted(variant_keys),
- window_start=window_start,
- window_end=window_end,
- limit=limit,
exposure=exposure,
+ variant_keys=scan_variant_keys,
+ search_start=anchor_floor,
+ run_end=run_end,
+ shared_hogql=shared_hogql,
)
+ if anchored_end is None:
+ # The anchor searched back to the floor and found no in-session exposure, so the floor is
+ # what the response reports: nothing newer went unread, and the bucket query would
+ # return the same empty list.
+ window_start = anchor_floor
+ window_end = run_end
+ candidate_session_ids: list[str] = []
+ scan_hit_cap = False
+ else:
+ window_end = anchored_end
+ window_start = max(experiment.start_date, window_end - timedelta(days=MAX_BUCKET_SCAN_DAYS))
+ candidate_session_ids, scan_hit_cap = _query_bucket_sessions(
+ team,
+ user,
+ experiment,
+ bucket=bucket,
+ considered=considered,
+ variant_keys=scan_variant_keys,
+ window_start=window_start,
+ window_end=window_end,
+ limit=limit,
+ exposure=exposure,
+ shared_hogql=shared_hogql,
+ )
result = SessionBucketScan(
candidate_session_ids=candidate_session_ids,
scan_hit_cap=scan_hit_cap,
@@ -324,6 +367,31 @@ def get_experiment_session_bucket(
return result
+def _restriction_signature(team: Team, user: User) -> str:
+ """The viewer's property restrictions, as a cache-key fragment.
+
+ Restrictions are compiled into the SQL, so unlike recording access they can't be re-filtered on
+ read; a restriction change has to miss the cache instead.
+ """
+ return json.dumps(
+ [
+ {
+ "name": restriction.name,
+ "property_type": restriction.property_type,
+ "group_type_index": restriction.group_type_index,
+ }
+ for restriction in sorted(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
+ key=lambda restriction: (
+ restriction.name,
+ restriction.property_type,
+ restriction.group_type_index if restriction.group_type_index is not None else -1,
+ ),
+ )
+ ]
+ )
+
+
def _cache_key(
team: Team,
user: User,
@@ -331,8 +399,8 @@ def _cache_key(
bucket: SessionBucket,
considered: list[MetricEventSource],
variant: Optional[str],
- window_start: datetime,
- window_end: datetime,
+ run_start: datetime,
+ run_end: datetime,
limit: int,
default_exposure_event: str,
) -> str:
@@ -344,37 +412,182 @@ def _cache_key(
bucket.value,
sorted(metric.metric_uuid for metric in considered),
variant,
- # The scan window moves with wall-clock time on a running experiment; rounding to the
- # minute keeps a burst of requests on one entry without pinning a stale window.
- window_start.replace(second=0, microsecond=0).isoformat(),
- window_end.replace(second=0, microsecond=0).isoformat(),
+ # The run window, not the scanned one, which is a function of the data inside it:
+ # keying on that would mean resolving the anchor before every lookup, hits included.
+ # Rounded to the minute so a burst of requests shares one entry as the run end moves.
+ run_start.replace(second=0, microsecond=0).isoformat(),
+ run_end.replace(second=0, microsecond=0).isoformat(),
# Part of the key even though the cut happens on read: the scan over-fetches a
# multiple of the limit, so a larger one looks further than a cached smaller one did.
limit,
# The rollout flag can flip which event the default exposure reads mid-window, and a
# scan computed on the other event must not be served after the flip.
default_exposure_event,
- # Property restrictions are compiled into the SQL, so unlike recording access they
- # can't be re-filtered on read; a restriction change has to miss the cache instead.
- [
- {
- "name": restriction.name,
- "property_type": restriction.property_type,
- "group_type_index": restriction.group_type_index,
- }
- for restriction in sorted(
- get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
- key=lambda restriction: (
- restriction.name,
- restriction.property_type,
- restriction.group_type_index if restriction.group_type_index is not None else -1,
- ),
- )
- ],
+ _restriction_signature(team, user),
]
)
digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
- return f"experiment_session_bucket_v4_{team.pk}_{user.pk}_{experiment.pk}_{digest}"
+ return f"experiment_session_bucket_v5_{team.pk}_{user.pk}_{experiment.pk}_{digest}"
+
+
+def _anchor_cache_key(
+ team: Team,
+ user: User,
+ experiment: Experiment,
+ *,
+ variant_keys: list[str],
+ search_start: datetime,
+ run_end: datetime,
+ exposure: SessionExposure,
+) -> str:
+ """Per (team, viewer, experiment, exposure, variants, run window).
+
+ Deliberately narrower than the bucket key: the anchor is the same timestamp whichever bucket or
+ metrics are asked for, so every mode and metric switch on one experiment shares this entry
+ rather than paying for the scan again.
+ """
+ spec = json.dumps(
+ [
+ variant_keys,
+ search_start.replace(second=0, microsecond=0).isoformat(),
+ run_end.replace(second=0, microsecond=0).isoformat(),
+ exposure.default_exposure_event,
+ exposure.variant_property,
+ exposure.used_fallback,
+ _restriction_signature(team, user),
+ ]
+ )
+ digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
+ return f"experiment_session_bucket_anchor_v1_{team.pk}_{user.pk}_{experiment.pk}_{digest}"
+
+
+@dataclass(frozen=True)
+class _WindowAnchor:
+ """A resolved scan-window end, wrapped so that a cached "no exposure in the run" reads as a
+ cache hit rather than a miss."""
+
+ window_end: Optional[datetime]
+
+
+def _anchor_floor(team: Team, *, run_start: datetime, run_end: datetime) -> datetime:
+ """The oldest timestamp the anchor may read, whichever of the two bounds is tighter.
+
+ Past the project's replay retention, every session the anchor could point at has already lost
+ its recording, so reading further only produces rows the recording lookup drops.
+ `MAX_ANCHOR_LOOKBACK_DAYS` then caps the long retention tiers.
+ """
+ lookback = min(retention_period_in_days(team.session_recording_retention_period), MAX_ANCHOR_LOOKBACK_DAYS)
+ return max(run_start, run_end - timedelta(days=lookback))
+
+
+def _resolve_window_end(
+ team: Team,
+ user: User,
+ experiment: Experiment,
+ *,
+ exposure: SessionExposure,
+ variant_keys: list[str],
+ search_start: datetime,
+ run_end: datetime,
+ shared_hogql: SharedHogQLDatabase,
+) -> Optional[datetime]:
+ """Where the scan window ends: `MAX_SESSION_DURATION_HOURS` past the latest in-session
+ exposure, capped at the end of the run. None when nothing from `search_start` on carries one.
+
+ The pad is what keeps the classification honest. A session's metric events can follow its
+ exposure, so a window that stopped at the last exposure would read a purchase fired after it as
+ absence, and a funnel finished after it as a drop-off.
+ """
+ if exposure.used_fallback and fallback_evidence_scan_is_unaffordable(team, experiment):
+ # The stamped-property condition carries no event name for ClickHouse to prune on, so
+ # anchoring would read every event the team captured in the run. The in-session recordings
+ # list refuses exactly this scan on these teams, so keep the recent-to-now window instead
+ # of buying the anchor at that price.
+ return run_end
+
+ cache_key = _anchor_cache_key(
+ team, user, experiment, variant_keys=variant_keys, search_start=search_start, run_end=run_end, exposure=exposure
+ )
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached.window_end
+
+ def latest_from(window_start: datetime, window_end: datetime) -> Optional[datetime]:
+ return _latest_session_exposure_at(
+ team,
+ user,
+ experiment,
+ exposure=exposure,
+ variant_keys=variant_keys,
+ window_start=window_start,
+ window_end=window_end,
+ shared_hogql=shared_hogql,
+ )
+
+ # The recent stretch first, and it settles the anchor on its own whenever it holds an exposure:
+ # every exposure outside it is older than every exposure inside it, so its latest is the run's
+ # latest. An experiment with current traffic therefore never reads its older days. The second
+ # probe stops where the first one started, which the first one has just found empty.
+ recent_start = max(search_start, run_end - timedelta(days=MAX_BUCKET_SCAN_DAYS))
+ latest = latest_from(recent_start, run_end)
+ if latest is None and recent_start > search_start:
+ latest = latest_from(search_start, recent_start)
+ window_end = None if latest is None else min(run_end, latest + timedelta(hours=MAX_SESSION_DURATION_HOURS))
+ safe_cache_set(cache_key, _WindowAnchor(window_end=window_end), timeout=SESSION_BUCKET_CACHE_TTL)
+ return window_end
+
+
+def _latest_session_exposure_at(
+ team: Team,
+ user: User,
+ experiment: Experiment,
+ *,
+ exposure: SessionExposure,
+ variant_keys: list[str],
+ window_start: datetime,
+ window_end: datetime,
+ shared_hogql: SharedHogQLDatabase,
+) -> Optional[datetime]:
+ """When a session last carried exposure evidence in this window, or None when none did.
+
+ The same exposure condition, variant keys and test-account filter the bucket query gets, so the
+ anchor is the latest exposure that query could count rather than a wider one. `count()` rides
+ the same scan because `max()` over no rows returns the epoch instead of NULL, which a window
+ would silently accept.
+ """
+ query = ast.SelectQuery(
+ select=[
+ ast.Call(name="max", args=[ast.Field(chain=["timestamp"])]),
+ ast.Call(name="count", args=[]),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=window_start),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=window_end),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.NotEq, left=ast.Field(chain=["$session_id"]), right=ast.Constant(value="")
+ ),
+ exposure.condition(variant_keys),
+ *get_test_accounts_filter(team, experiment.exposure_criteria),
+ ]
+ ),
+ )
+ response = execute_hogql_query(
+ query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers
+ )
+ rows = response.results or []
+ if not rows or not rows[0][1]:
+ return None
+ return rows[0][0]
def _resolve_requested_metrics(experiment: Experiment, metric_uuids: list[str]) -> list[MetricEventSource]:
@@ -538,6 +751,7 @@ def _query_bucket_sessions(
window_end: datetime,
limit: int,
exposure: SessionExposure,
+ shared_hogql: SharedHogQLDatabase,
) -> tuple[list[str], bool]:
def exposure_condition() -> ast.Expr:
return exposure.condition(variant_keys)
@@ -618,13 +832,6 @@ def _query_bucket_sessions(
# One query, so there is no union to hide an implicit per-branch limit — but the limit is
# still set explicitly, since an unset one would silently become HogQL's LIMIT 100.
- modifiers = create_default_modifiers_for_team(team)
- shared_hogql = SharedHogQLDatabase(
- # Postgres foreign-key lazy joins are the most expensive part of building the virtual
- # database and this query only reads events.
- database=Database.create_for(team=team, user=user, modifiers=modifiers, build_postgres_foreign_keys=False),
- modifiers=modifiers,
- )
response = execute_hogql_query(
query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers
)
diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.py
index 00003eb876b7..4611de0b191f 100644
--- a/products/experiments/backend/session_event_deltas.py
+++ b/products/experiments/backend/session_event_deltas.py
@@ -131,7 +131,7 @@ from products.experiments.backend.replay_linkage import (
exposed_persons_select,
resolve_exposure_linkage,
)
-from products.experiments.backend.session_exposure import never_session_linked_events
+from products.experiments.backend.session_exposure import MAX_SESSION_DURATION_HOURS, never_session_linked_events
# Tighter than MAX_BUCKET_SCAN_DAYS. The bucket scan filters by event name in its WHERE, so
# ClickHouse prunes on the events table's primary key; this one compares every event name there is
@@ -143,11 +143,6 @@ MAX_DELTA_SCAN_DAYS = 14
# variants stay covered over the same period — a comparison split across different stretches of time
# would be measuring the calendar as much as the variant.
MAX_DELTA_SCAN_SESSIONS = 20_000
-# How far back of a session's own events the scan has to reach once the window is clamped to what
-# the ceiling covers. The ceiling is resolved from each session's *last* activity, so a session that
-# began before that floor would otherwise be read from the middle, and the events it opened with
-# would go missing from a comparison that claims to have seen the session.
-MAX_SESSION_DURATION_HOURS = 24
# Ceiling on (event name x variant) rows one comparison ranks. Distinct event names per project are
# normally in the hundreds; a project that keys event names by id is what this is for.
MAX_DELTA_EVENT_ROWS = 10_000
diff --git a/products/experiments/backend/session_exposure.py b/products/experiments/backend/session_exposure.py
index 6c13a99cb696..8d211c17031c 100644
--- a/products/experiments/backend/session_exposure.py
+++ b/products/experiments/backend/session_exposure.py
@@ -30,6 +30,14 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
)
from products.experiments.backend.models.experiment import Experiment
+# How long a session can run, so a window anchored on one of the session's own events still covers
+# the rest of it. The two session-scoped surfaces read it in opposite directions. The delta scan
+# resolves its ceiling from each session's last activity, so it has to reach this far back or a
+# session that began earlier is read from the middle and the events it opened with go missing. The
+# bucket scan anchors on the last exposure, so it has to reach this far forward or the metric
+# events that follow that exposure read as absence.
+MAX_SESSION_DURATION_HOURS = 24
+
def never_session_linked_events(team: Team, event_names: frozenset[str]) -> frozenset[str]:
"""Event names never ingested with a `$session_id` property — only ever captured server-side, so
diff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.py
index cce2d5e9834d..d3d33a5661f8 100644
--- a/products/experiments/backend/test/test_session_buckets_api.py
+++ b/products/experiments/backend/test/test_session_buckets_api.py
@@ -15,19 +15,23 @@ import posthog.hogql.query as hogql_query_module
from posthog.clickhouse.query_tagging import Product, get_query_tags
from posthog.constants import AvailableFeature
from posthog.models import EventProperty, Team, User
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import uuid7
from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
+from products.experiments.backend import session_buckets
from products.experiments.backend.hogql_queries.exposure_query_logic import (
EXPERIMENT_EXPOSURE_EVENT,
EXPERIMENT_EXPOSURE_EVENT_CUTOFF,
EXPERIMENT_EXPOSURE_EVENT_FLAG,
)
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.session_buckets import MAX_BUCKET_METRICS, MAX_BUCKET_SCAN_DAYS, MAX_BUCKET_SOURCES
+from products.experiments.backend.session_exposure import MAX_SESSION_DURATION_HOURS
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from ee.api.test.base import APILicensedTest
@@ -173,6 +177,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
exposure_event: str = "$feature_flag_called",
distinct_id: str = "user1",
properties: Optional[dict[str, Any]] = None,
+ retention_days: Optional[int] = None,
) -> str:
"""One session: a recording, an exposure event for `variant` (unless None), and events.
@@ -187,6 +192,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
distinct_id=distinct_id,
first_timestamp=at,
last_timestamp=at + timedelta(minutes=30),
+ retention_period_days=retention_days,
)
if variant is not None:
_create_event(
@@ -740,7 +746,8 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
at=NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS + 5),
events=[("purchase", NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS + 5) + timedelta(minutes=5))],
)
- recent = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
+ recent_at = datetime(2026, 1, 9, 10, 0, tzinfo=UTC)
+ recent = self._session(at=recent_at, events=[("purchase", recent_at + timedelta(minutes=5))])
flush_persons_and_events()
response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])
@@ -750,7 +757,140 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
assert too_old not in data["session_ids"]
# The response says what it scanned, so the surface can state the omission rather than
# implying the bucket is empty beyond the clamp.
- assert data["date_from"] == (NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS)).isoformat().replace("+00:00", "Z")
+ window_end = recent_at + timedelta(hours=MAX_SESSION_DURATION_HOURS)
+ assert data["date_to"] == window_end.isoformat().replace("+00:00", "Z")
+ assert data["date_from"] == (window_end - timedelta(days=MAX_BUCKET_SCAN_DAYS)).isoformat().replace(
+ "+00:00", "Z"
+ )
+
+ def test_scan_window_follows_the_latest_exposure_once_traffic_has_stopped(self) -> None:
+ # A session from 45 days ago keeps its recording, and the anchor may look that far back,
+ # only on a project that keeps recordings for longer than the default 30 days.
+ self.team.session_recording_retention_period = "90d"
+ self.team.save()
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], start_date=NOW - timedelta(days=90))
+ last_exposure_at = NOW - timedelta(days=45)
+ # A recording outlives the scan gap only where the project keeps recordings past the
+ # default 30 days, which is the case this fix is for.
+ quiet = self._session(at=last_exposure_at - timedelta(days=1), retention_days=90)
+ late_buyer = self._session(
+ at=last_exposure_at,
+ events=[("purchase", last_exposure_at + timedelta(hours=2))],
+ retention_days=90,
+ )
+ flush_persons_and_events()
+
+ response = self._post_bucket(experiment, bucket="no_metric_activity", metric_uuids=[PURCHASE_METRIC["uuid"]])
+
+ data = response.json()
+ # A window ending at now covers a stretch this experiment stopped being exposed in, so
+ # every bucket answers "nothing matched" while exposed sessions sit just outside it.
+ assert data["session_ids"] == [quiet]
+ # The window reaches a session's length past the anchor, so the purchase this session
+ # fired after its exposure counts as activity instead of as absence.
+ assert late_buyer not in data["session_ids"]
+ window_end = last_exposure_at + timedelta(hours=MAX_SESSION_DURATION_HOURS)
+ assert data["date_to"] == window_end.isoformat().replace("+00:00", "Z")
+ assert data["date_from"] == (window_end - timedelta(days=MAX_BUCKET_SCAN_DAYS)).isoformat().replace(
+ "+00:00", "Z"
+ )
+
+ def test_the_stamped_fallback_keeps_the_recent_window_where_anchoring_is_unaffordable(self) -> None:
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ config.experiment_precomputation_enabled = True
+ config.save()
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ purchased = self._session(
+ variant=None,
+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],
+ properties={"$feature/checkout-cta": "test"},
+ )
+ quiet = self._session(
+ variant=None,
+ events=[("$pageview", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],
+ properties={"$feature/checkout-cta": "test"},
+ )
+ flush_persons_and_events()
+
+ response = self._post_bucket(experiment, bucket="no_metric_activity", metric_uuids=[PURCHASE_METRIC["uuid"]])
+
+ data = response.json()
+ assert data["used_exposure_fallback"] is True
+ assert purchased not in data["session_ids"]
+ assert data["session_ids"] == [quiet]
+ # The stamped condition names no event to prune on, so anchoring it would read every event
+ # the team captured in the run. These are the teams where the in-session recordings list
+ # refuses that scan outright, so the bucket keeps the window it can afford.
+ assert data["date_to"] == NOW.isoformat().replace("+00:00", "Z")
+
+ def test_a_run_with_no_in_session_exposure_reports_the_whole_run_as_scanned(self) -> None:
+ # Retention longer than the run, so the anchor's floor is the run's own start.
+ self.team.session_recording_retention_period = "90d"
+ self.team.save()
+ start = NOW - timedelta(days=60)
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], start_date=start)
+ # Sessions do carry the exposure event, just never for this flag, so the scan looks the
+ # event up rather than falling back to the stamped property.
+ self._session(flag_key="other-flag", events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
+ flush_persons_and_events()
+
+ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])
+
+ data = response.json()
+ assert data["session_ids"] == []
+ assert data["used_exposure_fallback"] is False
+ # The anchor read the whole run to find nothing, so no older stretch went unread. Reporting
+ # the 30-day clamp here would have the surface state an omission that never happened.
+ assert data["date_from"] == start.isoformat().replace("+00:00", "Z")
+ assert data["date_to"] == NOW.isoformat().replace("+00:00", "Z")
+
+ def test_the_window_anchor_is_resolved_once_across_bucket_requests(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], start_date=NOW - timedelta(days=90))
+ self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
+ flush_persons_and_events()
+
+ original = session_buckets._latest_session_exposure_at
+ anchor_scans = []
+
+ def _counting_anchor(*args: Any, **kwargs: Any) -> Any:
+ anchor_scans.append(kwargs["window_start"])
+ return original(*args, **kwargs)
+
+ with patch.object(session_buckets, "_latest_session_exposure_at", side_effect=_counting_anchor):
+ first = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])
+ second = self._post_bucket(experiment, bucket="no_metric_activity", metric_uuids=[PURCHASE_METRIC["uuid"]])
+
+ assert first.status_code == status.HTTP_200_OK, first.json()
+ assert second.status_code == status.HTTP_200_OK, second.json()
+ # The anchor is the same timestamp whichever bucket is asked for, so switching mode must not
+ # buy the scan again. One scan, and it read the recent stretch rather than the whole run:
+ # the run's older days can hold no later exposure than the days after them.
+ assert anchor_scans == [NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS)]
+
+ def test_the_anchor_stops_at_the_recording_retention_of_the_project(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], start_date=NOW - timedelta(days=365))
+ # Exposed 45 days ago on a project that keeps recordings for 30, so every session an older
+ # scan could reach has already lost its recording.
+ exposed_at = NOW - timedelta(days=45)
+ self._session(at=exposed_at, events=[("purchase", exposed_at + timedelta(minutes=5))])
+ flush_persons_and_events()
+
+ searched_from = []
+ original = session_buckets._latest_session_exposure_at
+
+ def _recording_anchor(*args: Any, **kwargs: Any) -> Any:
+ searched_from.append(kwargs["window_start"])
+ return original(*args, **kwargs)
+
+ with patch.object(session_buckets, "_latest_session_exposure_at", side_effect=_recording_anchor):
+ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])
+
+ data = response.json()
+ # Reaching back to the start of the run would read a year of the exposure event on every
+ # cold request, to find sessions the recording lookup then drops.
+ assert searched_from == [NOW - timedelta(days=30)]
+ assert data["session_ids"] == []
+ assert data["date_from"] == (NOW - timedelta(days=30)).isoformat().replace("+00:00", "Z")
def test_test_account_filtering_follows_the_exposure_criteria(self) -> None:
self.team.test_account_filters = [{"key": "$host", "value": "localhost", "operator": "is_not", "type": "event"}]
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 0ebe2cd5b177..36cc43335353 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2323,9 +2323,9 @@ export interface ExperimentSessionBucketResponseApi {
considered_metrics: ExperimentSessionBucketMetricApi[]
/** Requested metrics left out of the bucket because they can never match a recording, with the reason. They are reported rather than silently producing an empty result. */
excluded_metrics: ExperimentSessionBucketExcludedMetricApi[]
- /** Start of the window scanned: the experiment's run window, clamped to its most recent 30 days. Matches outside it are not returned. */
+ /** Start of the window scanned, never before the experiment started. At most 30 days before date_to when the scan found an exposure to anchor on. When it found none, how far back the search for one reached, which the project's recording retention bounds. Matches outside the window are not returned. */
date_from: string
- /** End of the window scanned: the experiment's end date, or now while it runs. */
+ /** End of the window scanned: 24 hours after the latest exposure captured in a session, capped at the experiment's end date or now. The pad covers the metric events a session fires after its exposure. The scan ends at the experiment's end date, or now while it runs, when that exposure can't be located, so an experiment whose exposures stopped long ago is still scanned where its sessions are. */
date_to: string
/** Whether the project's test-account filters were applied, following the experiment's exposure criteria, the same rule the experiment's recordings list uses. */
filter_test_accounts: boolean
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e326a07baa0e..faaaa769b6f2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -36554,9 +36554,9 @@ export namespace Schemas {
considered_metrics: ExperimentSessionBucketMetric[];
/** Requested metrics left out of the bucket because they can never match a recording, with the reason. They are reported rather than silently producing an empty result. */
excluded_metrics: ExperimentSessionBucketExcludedMetric[];
- /** Start of the window scanned: the experiment's run window, clamped to its most recent 30 days. Matches outside it are not returned. */
+ /** Start of the window scanned, never before the experiment started. At most 30 days before date_to when the scan found an exposure to anchor on. When it found none, how far back the search for one reached, which the project's recording retention bounds. Matches outside the window are not returned. */
date_from: string;
- /** End of the window scanned: the experiment's end date, or now while it runs. */
+ /** End of the window scanned: 24 hours after the latest exposure captured in a session, capped at the experiment's end date or now. The pad covers the metric events a session fires after its exposure. The scan ends at the experiment's end date, or now while it runs, when that exposure can't be located, so an experiment whose exposures stopped long ago is still scanned where its sessions are. */
date_to: string;
/** Whether the project's test-account filters were applied, following the experiment's exposure criteria, the same rule the experiment's recordings list uses. */
filter_test_accounts: boolean;