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.

feat(experiments): What-to-watch feature to highlight insightful recordings (#79190)

Marcel Poelkerd92011e22d8b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index e38e2690a3cb..07292c11e8cc 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -312,6 +312,7 @@ export const FEATURE_FLAGS = {
ERROR_TRACKING_RELATED_ISSUES: 'error-tracking-related-issues', // owner: #team-error-tracking
ERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-tracking
EVENT_MEDIA_PREVIEWS: 'event-media-previews', // owner: @alexlider
+ EXPERIMENT_BEHAVIOR_COMPARISON: 'experiment-behavior-comparison', // owner: @mp-hog #team-experiments
EXPERIMENT_FLAG_CLEANUP_PR: 'experiment-flag-cleanup-pr', // owner: @jurajmajerik #team-experiments
EXPERIMENT_RECORDINGS_TAB: 'experiment-recordings-tab', // owner: @mp-hog #team-experiments
EXPERIMENT_SESSION_REPLAYS_SKILL: 'experiment-session-replays-skill', // owner: @rodrigoi #team-experiments
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx
new file mode 100644
index 000000000000..a059845e799e
--- /dev/null
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx
@@ -0,0 +1,313 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown, IconInfo } from '@posthog/icons'
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+import { Experiment } from '~/types'
+
+import {
+ ExperimentWatchCardStrengthEnumApi,
+ ExperimentWatchCardKindEnumApi,
+ type ExperimentSessionEventDeltaResponseApi,
+ type ExperimentWatchCardApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import { experimentReplayTabLogic } from './experimentReplayTabLogic'
+import { VariantTag } from './VariantTag'
+
+const STRENGTH_WORD: Record<Exclude<ExperimentWatchCardStrengthEnumApi, 'only'>, string> = {
+ far_more: 'Far more common',
+ more: 'More common',
+ slightly_more: 'Slightly more common',
+}
+
+/**
+ * The one comparative sentence a card gets, in bands rather than numbers. The band comes from the
+ * conservative end of the difference; wording it as a multiple would put an effect size on screen,
+ * which is the results tab's job. Do not reintroduce one.
+ *
+ * `armKeys` is what the comparison actually pooled, not every variant the flag defines — a variant
+ * below the evidence floor was never in the "other variants" this card is measured against.
+ */
+function cardSentence(card: ExperimentWatchCardApi, armKeys: string[]): string {
+ if (card.kind === ExperimentWatchCardKindEnumApi.Metric) {
+ return card.metric_name ? `Watch the ${card.metric_name} metric happen` : 'Watch this metric event happen'
+ }
+ const others =
+ armKeys.length > 2 ? 'the other variants' : (armKeys.find((key) => key !== card.variant) ?? 'the other variant')
+ if (card.strength === ExperimentWatchCardStrengthEnumApi.Only) {
+ return `Seen here, never in ${others}`
+ }
+ return `${STRENGTH_WORD[card.strength ?? ExperimentWatchCardStrengthEnumApi.More]} than in ${others}`
+}
+
+function WatchCard({
+ card,
+ selected,
+ armKeys,
+ onSelect,
+}: {
+ card: ExperimentWatchCardApi
+ selected: boolean
+ armKeys: string[]
+ onSelect: (card: ExperimentWatchCardApi | null) => void
+}): JSX.Element {
+ return (
+ // The whole card is one control, so the control is a real button rather than a click
+ // handler on the card: picking a card is the only thing to do on this shelf, and a
+ // clickable div can't be reached or fired from the keyboard.
+ <LemonCard hoverEffect focused={selected} className="w-60 shrink-0 p-0" data-attr="experiment-watch-card">
+ <button
+ type="button"
+ aria-pressed={selected}
+ onClick={() => onSelect(selected ? null : card)}
+ className="flex w-full cursor-pointer flex-col gap-1 p-3 text-left"
+ >
+ <VariantTag variantKey={card.variant} />
+ <div className="break-all text-sm font-semibold leading-tight">{card.event}</div>
+ <div className="text-xs text-secondary">{cardSentence(card, armKeys)}</div>
+ <div className="mt-1 flex w-full items-center justify-between text-xs">
+ <span className="text-secondary">{pluralize(card.recording_count, 'recording')}</span>
+ <span className="font-medium">{selected ? 'Showing below' : 'Watch'}</span>
+ </div>
+ </button>
+ </LemonCard>
+ )
+}
+
+function Shelf({
+ title,
+ note,
+ cards,
+ selectedCard,
+ armKeys,
+ onSelect,
+}: {
+ title: string
+ note?: string
+ cards: ExperimentWatchCardApi[]
+ selectedCard: ExperimentWatchCardApi | null
+ armKeys: string[]
+ onSelect: (card: ExperimentWatchCardApi | null) => void
+}): JSX.Element | null {
+ if (cards.length === 0) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-baseline gap-2">
+ <span className="text-xs font-semibold uppercase tracking-wide text-secondary">{title}</span>
+ {note && <span className="text-xs text-muted">{note}</span>}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {cards.map((card) => (
+ <WatchCard
+ key={`${card.kind}-${card.event}-${card.variant}`}
+ card={card}
+ selected={
+ selectedCard !== null &&
+ selectedCard.event === card.event &&
+ selectedCard.variant === card.variant &&
+ selectedCard.kind === card.kind
+ }
+ armKeys={armKeys}
+ onSelect={onSelect}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+/** The toggle alone, so it can sit in the tab's filter row while the shelves render below it. */
+export function ExperimentBehaviorComparisonToggle({ experiment }: { experiment: Experiment }): JSX.Element | null {
+ const logic = experimentReplayTabLogic({ experiment })
+ const { behaviorComparisonAvailable, behaviorComparisonOpen } = useValues(logic)
+ const { toggleBehaviorComparison } = useActions(logic)
+
+ if (!behaviorComparisonAvailable) {
+ return null
+ }
+
+ return (
+ <LemonButton
+ size="small"
+ type="secondary"
+ // One glyph rotated rather than a chevron pair: IconChevronRight is drawn three times
+ // taller than IconChevronDown in this set, so the two states would change size.
+ icon={<IconChevronDown className={cn('transition-transform', !behaviorComparisonOpen && '-rotate-90')} />}
+ onClick={() => toggleBehaviorComparison()}
+ aria-expanded={behaviorComparisonOpen}
+ tooltip="Groups of recordings worth watching: behavior one variant shows more of, friction, and your metric events happening on screen."
+ data-attr="experiment-behavior-comparison-toggle"
+ >
+ What to watch
+ </LemonButton>
+ )
+}
+
+export function ExperimentBehaviorComparison({ experiment }: { experiment: Experiment }): JSX.Element | null {
+ const logic = experimentReplayTabLogic({ experiment })
+ const {
+ behaviorComparisonAvailable,
+ behaviorComparisonOpen,
+ sessionEventDeltas,
+ sessionEventDeltasLoading,
+ sessionEventDeltasError,
+ selectedWatchCard,
+ } = useValues(logic)
+ const { selectWatchCard, loadSessionEventDeltas } = useActions(logic)
+
+ // Nothing at all when closed, rather than an empty spacer: the toggle lives in the filter row
+ // now, so a wrapper left behind here would push the recordings list down for no reason.
+ if (!behaviorComparisonAvailable || !behaviorComparisonOpen) {
+ return null
+ }
+
+ return (
+ <div className="mb-4">
+ {sessionEventDeltasError !== null ? (
+ <div className="flex items-center gap-2 text-xs text-secondary">
+ <span>Couldn't pick recordings to watch: {sessionEventDeltasError}</span>
+ <LemonButton size="xsmall" type="secondary" onClick={() => loadSessionEventDeltas()}>
+ Try again
+ </LemonButton>
+ </div>
+ ) : sessionEventDeltasLoading || !sessionEventDeltas ? (
+ <div className="flex items-center gap-2 text-xs text-secondary">
+ <Spinner textColored />
+ <span>Comparing what happened in each variant's sessions…</span>
+ </div>
+ ) : (
+ <WatchShelves deltas={sessionEventDeltas} selectedCard={selectedWatchCard} onSelect={selectWatchCard} />
+ )}
+ </div>
+ )
+}
+
+function WatchShelves({
+ deltas,
+ selectedCard,
+ onSelect,
+}: {
+ deltas: ExperimentSessionEventDeltaResponseApi
+ selectedCard: ExperimentWatchCardApi | null
+ onSelect: (card: ExperimentWatchCardApi | null) => void
+}): JSX.Element {
+ if (deltas.too_early) {
+ return (
+ <LemonBanner type="info">
+ Too early to compare behavior: this needs at least{' '}
+ {pluralize(deltas.min_arm_persons, 'exposed person', 'exposed people')} in two variants, and has{' '}
+ {deltas.arms.map((arm) => `${humanFriendlyNumber(arm.persons)} in ${arm.key}`).join(', ')}.
+ </LemonBanner>
+ )
+ }
+
+ // What the comparison pooled, which is not every variant the flag defines: one below the
+ // evidence floor is left out of the comparison, so a card's sentence must not name it as
+ // something the card was measured against.
+ const armKeys = deltas.arms.filter((arm) => arm.persons >= deltas.min_arm_persons).map((arm) => arm.key)
+ const behaviorCards = deltas.cards.filter((card) => card.kind === ExperimentWatchCardKindEnumApi.Behavior)
+ const frictionCards = deltas.cards.filter((card) => card.kind === ExperimentWatchCardKindEnumApi.Friction)
+ const metricCards = deltas.cards.filter((card) => card.kind === ExperimentWatchCardKindEnumApi.Metric)
+
+ return (
+ <div className="flex flex-col gap-3">
+ <ShelfCaption deltas={deltas} />
+ {deltas.cards.length === 0 ? (
+ <div className="text-xs text-secondary">
+ No variant shows clearly different behavior in its recorded sessions yet. Differences small enough
+ to be chance don't get a card, so this can change as more people are exposed.
+ </div>
+ ) : (
+ <>
+ <Shelf
+ title="Behaves differently"
+ cards={behaviorCards}
+ selectedCard={selectedCard}
+ armKeys={armKeys}
+ onSelect={onSelect}
+ />
+ <Shelf
+ title="Friction"
+ cards={frictionCards}
+ selectedCard={selectedCard}
+ armKeys={armKeys}
+ onSelect={onSelect}
+ />
+ <Shelf
+ title="Metrics"
+ note="See your metric events happen. The Results tab measures them."
+ cards={metricCards}
+ selectedCard={selectedCard}
+ armKeys={armKeys}
+ onSelect={onSelect}
+ />
+ </>
+ )}
+ </div>
+ )
+}
+
+/**
+ * Read before the cards, not after them: what a reader has to know to interpret a shelf is that it
+ * points at recordings rather than measuring anything, and the window it actually covered. The
+ * full method sits behind the info icon.
+ */
+function ShelfCaption({ deltas }: { deltas: ExperimentSessionEventDeltaResponseApi }): JSX.Element {
+ // A window that ran out inside a single day reads wrong as two identical dates, and "Aug 3 to
+ // Aug 3" hides that only a few hours were covered.
+ const sameDay = dayjs(deltas.date_from).isSame(dayjs(deltas.date_to), 'day')
+ const format = sameDay ? 'MMM D, HH:mm' : 'MMM D'
+ const details = [
+ 'Each variant is compared against the others on which events people did, counting each person once, in the first session they were exposed in. Cards only appear where the difference is too big to be chance, and only with recordings that actually exist.',
+ 'Page views, autocaptures and the exposure event are never compared, since their names describe a mechanism rather than something a person did.',
+ deltas.metric_events.length > 0
+ ? `The events this experiment measures (${deltas.metric_events.join(', ')}) are never compared here either: the Results tab states what happened to them. Their cards only link to recordings.`
+ : null,
+ deltas.filter_test_accounts ? 'Test accounts are excluded.' : null,
+ deltas.multiple_variant_persons > 0
+ ? `${pluralize(deltas.multiple_variant_persons, 'person', 'people')} saw more than one variant and ${
+ deltas.multiple_variant_persons === 1 ? 'is' : 'are'
+ } left out.`
+ : null,
+ deltas.used_exposure_fallback
+ ? 'Sessions are matched on the feature flag being active, since no exposure event can be matched to a recording here.'
+ : null,
+ deltas.sessions_truncated
+ ? 'The experiment has more exposed sessions than one comparison covers, so the window is the most recent stretch that fits, not the whole run.'
+ : null,
+ deltas.events_truncated ? 'The project has more event types than one comparison can rank.' : null,
+ ].filter(Boolean)
+
+ return (
+ <div className="flex items-center gap-1 text-xs text-secondary">
+ <span>
+ These highlight which recordings might be worth watching. They don't say which variant is doing better,
+ the way metrics do. From recorded sessions between {dayjs(deltas.date_from).format(format)} and{' '}
+ {dayjs(deltas.date_to).format(format)}.
+ </span>
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-1">
+ {details.map((detail, index) => (
+ <span key={index}>{detail}</span>
+ ))}
+ </div>
+ }
+ >
+ <IconInfo className="shrink-0 text-sm" />
+ </Tooltip>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index fe11eed3d0f5..9c0181a53b8b 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -25,6 +25,7 @@ import { SummarizeSessionReplaysButton } from '../components/SummarizeSessionRep
import { isLaunched } from '../experimentStatus'
import { NOT_A_FUNNEL_REASON } from '../utils'
import { EXPOSURE_FALLBACK_NOTICE, EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
+import { ExperimentBehaviorComparison, ExperimentBehaviorComparisonToggle } from './ExperimentBehaviorComparison'
import {
ExperimentReplayMetricFilterMode,
ExperimentReplayMetricOption,
@@ -301,6 +302,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
</DropdownMenuContent>
</DropdownMenu>
)}
+ <ExperimentBehaviorComparisonToggle experiment={experiment} />
<div className="ml-auto">
<SummarizeSessionReplaysButton experiment={experiment} />
</div>
@@ -325,6 +327,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
)}
</div>
)}
+ <ExperimentBehaviorComparison experiment={experiment} />
<div className="SessionRecordingPlaylistHeightWrapper">
<SessionRecordingsPlaylist
logicKey={`experiment-${experiment.id}`}
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index ea4d1c557afb..dc37fb2e5272 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -19,6 +19,7 @@ import {
import {
experimentsSessionBucketsCreate,
experimentsSessionContextsCreate,
+ experimentsSessionEventDeltasCreate,
} from 'products/experiments/frontend/generated/api'
import {
@@ -36,6 +37,7 @@ jest.mock('lib/utils/product-intents', () => ({
jest.mock('products/experiments/frontend/generated/api', () => ({
experimentsSessionContextsCreate: jest.fn().mockResolvedValue({ results: [] }),
experimentsSessionBucketsCreate: jest.fn(),
+ experimentsSessionEventDeltasCreate: jest.fn(),
}))
const BUCKET_RESPONSE = {
@@ -48,6 +50,35 @@ const BUCKET_RESPONSE = {
filter_test_accounts: true,
}
+const DELTA_RESPONSE = {
+ cards: [
+ {
+ kind: 'behavior',
+ event: 'pricing_faq',
+ variant: 'test',
+ strength: 'far_more',
+ metric_name: null,
+ recording_count: 2,
+ session_ids: ['card-session-1', 'card-session-2'],
+ },
+ ],
+ arms: [
+ { key: 'control', persons: 100, sessions: 140 },
+ { key: 'test', persons: 100, sessions: 138 },
+ ],
+ multiple_variant_persons: 0,
+ multiple_variant_handling: 'exclude',
+ metric_events: [],
+ date_from: '2026-01-01T00:00:00Z',
+ date_to: '2026-02-01T00:00:00Z',
+ filter_test_accounts: true,
+ used_exposure_fallback: false,
+ sessions_truncated: false,
+ events_truncated: false,
+ min_arm_persons: 50,
+ too_early: false,
+}
+
const PURCHASE_METRIC = {
kind: NodeKind.ExperimentMetric,
metric_type: ExperimentMetricType.MEAN,
@@ -105,6 +136,8 @@ describe('experimentReplayTabLogic', () => {
;(experimentsSessionContextsCreate as jest.Mock).mockClear()
;(experimentsSessionBucketsCreate as jest.Mock).mockClear()
;(experimentsSessionBucketsCreate as jest.Mock).mockResolvedValue(BUCKET_RESPONSE)
+ ;(experimentsSessionEventDeltasCreate as jest.Mock).mockClear()
+ ;(experimentsSessionEventDeltasCreate as jest.Mock).mockResolvedValue(DELTA_RESPONSE)
seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')
seenTogetherSpy.mockResolvedValue(ALL_LINKABLE)
logic = experimentReplayTabLogic({ experiment: EXPERIMENT })
@@ -830,4 +863,101 @@ describe('experimentReplayTabLogic', () => {
sidebar.unmount()
})
+
+ it('runs the variant comparison only once the panel is opened', async () => {
+ // It is the heaviest read on this tab and most visits don't want it, so mounting the tab
+ // must not fire it.
+ expect(experimentsSessionEventDeltasCreate).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => {
+ logic.actions.toggleBehaviorComparison()
+ }).toFinishAllListeners()
+
+ expect(experimentsSessionEventDeltasCreate).toHaveBeenCalledTimes(1)
+ expect(logic.values.sessionEventDeltas).toEqual(DELTA_RESPONSE)
+ })
+
+ it('does not fire a duplicate comparison when the shelf is closed and reopened mid-load', async () => {
+ let resolveLoad: (value: unknown) => void = () => {}
+ ;(experimentsSessionEventDeltasCreate as jest.Mock).mockImplementation(
+ () => new Promise((resolve) => (resolveLoad = resolve))
+ )
+
+ logic.actions.toggleBehaviorComparison()
+ await expectLogic(logic).toDispatchActions(['loadSessionEventDeltas'])
+
+ logic.actions.toggleBehaviorComparison()
+ logic.actions.toggleBehaviorComparison()
+ await expectLogic(logic).toMatchValues({ sessionEventDeltasLoading: true })
+
+ expect(experimentsSessionEventDeltasCreate).toHaveBeenCalledTimes(1)
+
+ resolveLoad(DELTA_RESPONSE)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.sessionEventDeltas).toEqual(DELTA_RESPONSE)
+ })
+
+ it("shows a selected card's recordings, in the variant the card belongs to", 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'])
+
+ await expectLogic(logic, () => {
+ logic.actions.selectWatchCard(DELTA_RESPONSE.cards[0] as any)
+ }).toFinishAllListeners()
+
+ // The variant facet follows the card, the capped bucket is left behind so the card's own
+ // session set takes its place, and the card survives that mode change rather than being
+ // cleared by it. The metric selection goes with the mode: kept, "didn't fire Purchase"
+ // would silently have become "fired Purchase".
+ expect(logic.values.selectedVariantKey).toBe('test')
+ expect(logic.values.metricFilterMode).toBe('fired_all')
+ expect(logic.values.selectedMetricUuids).toEqual([])
+ expect(logic.values.recordingsFilters.session_ids).toEqual(['card-session-1', 'card-session-2'])
+ // The card's ids already encode the event condition, so no event filter is added on top —
+ // only the exposure filter stays, keeping the list's definition visible.
+ expect(logic.values.recordingsFilters.filter_group.values).toEqual([
+ {
+ type: FilterLogicalOperator.And,
+ values: [...getViewRecordingFiltersForVariant(EXPERIMENT, 'test')],
+ },
+ ])
+ })
+
+ it.each([
+ ['the variant facet moves', (): void => logic.actions.setSelectedVariantKey('control')],
+ ['a metric is picked', (): void => logic.actions.setMetricSelected('metric-purchase', true)],
+ ['the shelf is closed', (): void => logic.actions.toggleBehaviorComparison()],
+ ])('drops the selected card when %s', async (_name: string, moveFacet: () => void) => {
+ await expectLogic(logic, () => {
+ logic.actions.toggleBehaviorComparison()
+ logic.actions.selectWatchCard(DELTA_RESPONSE.cards[0] as any)
+ }).toFinishAllListeners()
+ expect(logic.values.recordingsFilters.session_ids).toEqual(['card-session-1', 'card-session-2'])
+
+ await expectLogic(logic, moveFacet).toFinishAllListeners()
+
+ // Left stacked these contradict rather than compose: the card's ids are one variant's and
+ // AND to an empty list under another, a metric picked on top is dropped from the query
+ // while still reading as applied, and a closed shelf leaves no way to deselect.
+ expect(logic.values.selectedWatchCard).toBeNull()
+ expect(logic.values.recordingsFilters.session_ids).toBeUndefined()
+ })
+
+ it("follows the playlist when the card's recordings are cleared there", async () => {
+ await expectLogic(logic, () => {
+ logic.actions.selectWatchCard(DELTA_RESPONSE.cards[0] as any)
+ }).toFinishAllListeners()
+
+ // Without following it the tab would push the same session ids straight back, and the
+ // playlist's own "Show all" control would look broken.
+ await expectLogic(logic, () => {
+ logic.actions.playlistFiltersChanged({
+ ...logic.values.recordingsFilters,
+ session_ids: undefined,
+ })
+ }).toMatchValues({ selectedWatchCard: null })
+ })
})
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index dc1aac16325e..8fba0990c10d 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -46,10 +46,13 @@ import {
import {
experimentsSessionBucketsCreate,
experimentsSessionContextsCreate,
+ experimentsSessionEventDeltasCreate,
} from 'products/experiments/frontend/generated/api'
import type {
ExperimentSessionBucketResponseApi,
ExperimentSessionBucketEnumApi,
+ ExperimentSessionEventDeltaResponseApi,
+ ExperimentWatchCardApi,
} from 'products/experiments/frontend/generated/api.schemas'
import type { ExperimentIdType } from '../../../types'
@@ -153,6 +156,8 @@ export interface experimentReplayTabLogicValues {
linkabilityLoaded: boolean // viewRecordingsLinkabilityLogic
seenTogetherMapLoading: boolean // viewRecordingsLinkabilityLogic
unlinkableEventNames: Set<string> // viewRecordingsLinkabilityLogic
+ behaviorComparisonAvailable: boolean
+ behaviorComparisonOpen: boolean
bucketSessionIds: string[] | undefined
effectiveMetricUuids: string[]
effectiveVariantKey: string | null
@@ -163,10 +168,14 @@ export interface experimentReplayTabLogicValues {
recordingsFilters: RecordingUniversalFilters
selectedMetricUuids: string[]
selectedVariantKey: string | null
+ selectedWatchCard: ExperimentWatchCardApi | null
sessionBucket: ExperimentSessionBucket | null
sessionBucketError: string | null
sessionBucketLoading: boolean
sessionBucketRequest: ExperimentSessionBucketRequest | null
+ sessionEventDeltas: ExperimentSessionEventDeltaResponseApi | null
+ sessionEventDeltasError: string | null
+ sessionEventDeltasLoading: boolean
usingExposureFallback: boolean
variantKeys: string[]
}
@@ -239,6 +248,21 @@ export interface experimentReplayTabLogicActions {
} | null
payload?: unknown
}
+ loadSessionEventDeltas: (_?: unknown) => unknown
+ loadSessionEventDeltasFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSessionEventDeltasSuccess: (
+ sessionEventDeltas: ExperimentSessionEventDeltaResponseApi,
+ payload?: unknown
+ ) => {
+ sessionEventDeltas: ExperimentSessionEventDeltaResponseApi
+ payload?: unknown
+ }
playlistFiltersChanged: (filters: RecordingUniversalFilters) => {
filters: RecordingUniversalFilters
}
@@ -254,6 +278,9 @@ export interface experimentReplayTabLogicActions {
reportTabViewed: () => {
value: true
}
+ selectWatchCard: (card: ExperimentWatchCardApi | null) => {
+ card: ExperimentWatchCardApi | null
+ }
setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => {
mode: ExperimentReplayMetricFilterMode
}
@@ -267,6 +294,9 @@ export interface experimentReplayTabLogicActions {
setSelectedVariantKey: (variantKey: string | null) => {
variantKey: string | null
}
+ toggleBehaviorComparison: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -274,6 +304,7 @@ export interface experimentReplayTabLogicMeta {
key: ExperimentIdType
__keaTypeGenInternalSelectorTypes: {
variantKeys: (arg: any) => string[]
+ behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => boolean
exposureUnlinkable: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean
usingExposureFallback: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean
effectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null
@@ -306,6 +337,7 @@ export interface experimentReplayTabLogicMeta {
unlinkableEventNames: Set<string>,
seenTogetherMapLoading: boolean,
bucketSessionIds: string[] | undefined,
+ selectedWatchCard: ExperimentWatchCardApi | null,
arg: any
) => RecordingUniversalFilters
}
@@ -361,6 +393,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
playlistFiltersChanged: (filters: RecordingUniversalFilters) => ({ filters }),
recordingsLoaded: (sessionIds: string[]) => ({ sessionIds }),
recordingOpened: (sessionId: string) => ({ sessionId }),
+ toggleBehaviorComparison: true,
+ selectWatchCard: (card: ExperimentWatchCardApi | null) => ({ card }),
prefetchSessionContexts: (sessionIds: string[]) => ({ sessionIds }),
reportTabViewed: true,
}),
@@ -412,6 +446,19 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
},
},
],
+ sessionEventDeltas: [
+ null as ExperimentSessionEventDeltaResponseApi | null,
+ {
+ loadSessionEventDeltas: async (_: unknown = null, breakpoint) => {
+ const response = await experimentsSessionEventDeltasCreate(
+ String(values.currentProjectId),
+ Number(props.experiment.id)
+ )
+ breakpoint()
+ return response
+ },
+ },
+ ],
})),
reducers({
// null = "All" (every exposed session, regardless of variant). Persisted (keyed per
@@ -422,6 +469,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
{ persist: true },
{
setSelectedVariantKey: (_, { variantKey }) => variantKey,
+ // A card's recordings are one variant's, so the facet moves with it — visibly, so
+ // nothing narrows unannounced. Here rather than from a listener dispatching
+ // setSelectedVariantKey, which would let that action stay the user's own and so
+ // able to clear the card below without clearing the one just selected.
+ selectWatchCard: (state: string | null, { card }) => (card ? card.variant : state),
},
],
// Empty = no metric filter. Every selected metric narrows the playlist further (AND) —
@@ -436,6 +488,9 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
selected
? [...state.filter((uuid) => uuid !== metricUuid), metricUuid]
: state.filter((uuid) => uuid !== metricUuid),
+ // Cleared alongside the mode reset below. Carrying a selection through would invert
+ // what it meant: "didn't fire this metric" would silently become "fired it".
+ selectWatchCard: (state, { card }) => (card ? [] : state),
},
],
// Persisted with the facets it composes with. 'fired_all' keeps the client-side event
@@ -445,6 +500,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
{ persist: true },
{
setMetricFilterMode: (_, { mode }) => mode,
+ // A bucket answers its own question with a capped session set, which would fight the
+ // card's own session set. Reset here rather than from a listener: dispatching
+ // setMetricFilterMode would clear the card this action just selected.
+ selectWatchCard: (state, { card }) =>
+ card ? ('fired_all' as ExperimentReplayMetricFilterMode) : state,
},
],
// The playlist's most recently loaded page, kept so opening a recording can re-warm
@@ -467,12 +527,54 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
loadSessionBucketFailure: (_, { error, errorObject }) => errorObject?.detail || error || 'unknown',
},
],
+ // The comparison is the heaviest read on this tab, so it is opened rather than loaded with
+ // the tab. Not persisted: reopening the tab shouldn't silently re-run it.
+ behaviorComparisonOpen: [
+ false,
+ {
+ toggleBehaviorComparison: (open: boolean) => !open,
+ },
+ ],
+ // Same discipline as the bucket error: a failed comparison must not fall through to an
+ // empty list, which would read as "the variants behaved the same".
+ sessionEventDeltasError: [
+ null as string | null,
+ {
+ loadSessionEventDeltas: () => null,
+ loadSessionEventDeltasSuccess: () => null,
+ loadSessionEventDeltasFailure: (_, { error, errorObject }) => errorObject?.detail || error || 'unknown',
+ },
+ ],
+ // The card whose recordings the playlist is showing, kept apart from the metric
+ // selection: its session set comes from the shelf rather than from the experiment's
+ // metrics.
+ selectedWatchCard: [
+ null as ExperimentWatchCardApi | null,
+ {
+ selectWatchCard: (_, { card }) => card,
+ // Any facet the user moves themselves replaces the question the list answers, so
+ // the two never stack. Left stacked they don't compose, they contradict: a card's
+ // ids are one variant's and AND to an empty list under another, while a metric
+ // picked on top is dropped from the query but still reads as applied in the
+ // trigger and the caption.
+ setMetricFilterMode: () => null,
+ setSelectedVariantKey: () => null,
+ setMetricSelected: () => null,
+ // Closing the shelf takes away the only way to deselect, so the list would stay
+ // narrowed with nothing on screen saying why.
+ toggleBehaviorComparison: () => null,
+ },
+ ],
}),
selectors({
variantKeys: [
() => [(_, props) => props.experiment],
(experiment: Experiment): string[] => getExperimentVariants(experiment).map((variant) => variant.key),
],
+ behaviorComparisonAvailable: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.EXPERIMENT_BEHAVIOR_COMPARISON],
+ ],
// Exposure is the whole list here, so an unmatchable exposure event with no fallback means
// there is nothing to show at all. Only custom exposure criteria end up here: the default
// exposure branch always has the `$feature/<flag_key>` fallback. Fails open while the
@@ -672,6 +774,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
s.unlinkableEventNames,
s.seenTogetherMapLoading,
s.bucketSessionIds,
+ s.selectedWatchCard,
(_, props) => props.experiment,
],
(
@@ -681,6 +784,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
unlinkableEventNames: Set<string>,
seenTogetherMapLoading: boolean,
bucketSessionIds: string[] | undefined,
+ selectedWatchCard: ExperimentWatchCardApi | null,
experiment: Experiment
): RecordingUniversalFilters => {
// A recordings query carries a single AND/OR operand across the whole flattened
@@ -699,7 +803,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
// fail-open posture every linkability consumer shares.
const seenFilters = new Set<string>()
const metricFilters =
- seenTogetherMapLoading || bucketSessionIds !== undefined
+ seenTogetherMapLoading || bucketSessionIds !== undefined || selectedWatchCard !== null
? // A bucket already encodes the metric condition in the session set it
// returns, so also ANDing the event filters would narrow it a second time.
[]
@@ -729,10 +833,12 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
).filters
return {
...DEFAULT_RECORDING_FILTERS,
- // The exposure filter stays in place alongside the bucket: the returned ids are
- // a subset of the exposed sessions, so this only keeps the list's definition
- // visible in the filter UI.
- session_ids: bucketSessionIds,
+ // The exposure filter stays in place alongside the bucket or card: their ids
+ // are a subset of the exposed sessions, so this only keeps the list's
+ // definition visible in the filter UI. A card's recordings are pre-checked
+ // against replay existence, so unlike an event filter this list can't come
+ // back empty.
+ session_ids: selectedWatchCard ? selectedWatchCard.session_ids : bucketSessionIds,
date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,
date_to: experiment.end_date ?? null,
filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,
@@ -779,6 +885,20 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
) {
actions.setMetricFilterMode('fired_all')
}
+ // The playlist's own "Show all" control clears session_ids; when a card put them
+ // there, that is the same intent as leaving the card, so follow it rather than
+ // pushing the ids straight back.
+ if (values.selectedWatchCard !== null && filters.session_ids == null) {
+ actions.selectWatchCard(null)
+ }
+ },
+ // Opening the panel is what runs the comparison — it is the heaviest read here, and most
+ // visits to the tab don't want it. Reopening reuses what's loaded or lets a pending load
+ // finish rather than firing a duplicate; the server-side cache covers a deliberate reload.
+ toggleBehaviorComparison: () => {
+ if (values.behaviorComparisonOpen && !values.sessionEventDeltas && !values.sessionEventDeltasLoading) {
+ actions.loadSessionEventDeltas()
+ }
},
// 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
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 3074fd495e14..b251bf887c64 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -585,6 +585,21 @@ class SessionBucketsSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "200/hour"
+# The experiment session-event-delta endpoint compares every event name in an experiment's recent
+# window, so unlike the bucket scan beside it there is no event-name predicate for ClickHouse to
+# prune on and one call is the heaviest in this family. Same project-wide bucketing and same
+# session-authenticated caller, at a lower rate again: the panel is opened deliberately rather than
+# loaded with the tab, and repeats hit a 15-minute server-side cache.
+class SessionEventDeltasBurstRateThrottle(_TeamBucketRateThrottle):
+ scope = "session_event_deltas_burst"
+ rate = "10/minute"
+
+
+class SessionEventDeltasSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "session_event_deltas_sustained"
+ rate = "100/hour"
+
+
class _AIThrottleBase(UserRateThrottle):
action_name: str
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 3e6bc51e7e26..1f7e6ec3fc71 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -665,6 +665,12 @@ SPECTACULAR_SETTINGS = {
"PropertyGroupOperator": ["AND", "OR"],
# `bucket` is a generic field name; name the experiment recordings bucket set explicitly.
"ExperimentSessionBucketEnum": ["fired_any", "no_metric_activity", "funnel_dropoff"],
+ # `strength` and `kind` are generic enough that the next one added anywhere would collide,
+ # and `multiple_variant_handling` would otherwise generate a bare `MultipleVariantHandling`
+ # sitting next to the schema type of the same name. One prefix for all three.
+ "ExperimentWatchCardKindEnum": ["behavior", "friction", "metric"],
+ "ExperimentWatchCardStrengthEnum": ["only", "far_more", "more", "slightly_more"],
+ "ExperimentWatchMultipleVariantHandlingEnum": ["exclude", "first_seen"],
# Account.slack_summary_cadence and AccountChannelSummary.cadence share the same
# daily/weekly/monthly choice set; pin one name for both.
"SlackSummaryCadenceEnum": ["daily", "weekly", "monthly"],
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 865feaef142a..f479146ba0a5 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -22,6 +22,7 @@ from posthog.schema import (
ExperimentApiMetric,
ExperimentParameters,
ExperimentRunningTimeCalculation,
+ MultipleVariantHandling,
)
from posthog.api.documentation import FeatureFlagFiltersSchemaSerializer
@@ -48,6 +49,13 @@ from products.experiments.backend.models.experiment import (
from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICES
from products.experiments.backend.session_buckets import MAX_BUCKET_SCAN_DAYS, MAX_SESSION_BUCKET_LIMIT, SessionBucket
from products.experiments.backend.session_context import MAX_SESSION_CONTEXT_BATCH
+from products.experiments.backend.session_event_deltas import (
+ MAX_CARD_RECORDINGS,
+ MAX_DELTA_SCAN_DAYS,
+ MAX_FALLBACK_DELTA_SCAN_DAYS,
+ DeltaStrength,
+ WatchCardKind,
+)
from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer
from products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_error
@@ -1866,3 +1874,177 @@ class ExperimentSessionBucketResponseSerializer(serializers.Serializer):
"event, so a returning user can appear under a variant they were re-bucketed into later."
)
)
+
+
+class ExperimentSessionEventDeltaRequestSerializer(serializers.Serializer):
+ """The watch cards endpoint takes no parameters: the shelf is computed per experiment, every
+ variant at once."""
+
+
+class ExperimentWatchCardSerializer(serializers.Serializer):
+ """One group of recordings worth opening, and the sentence that justifies it.
+
+ Deliberately no rate, no ratio and no person count: a precise number next to an event name is
+ an effect size, and the experiment's results publish those for everything it measures, computed
+ over a different window and a different unit. The only number here is how many recordings the
+ card can actually show.
+ """
+
+ kind = serializers.ChoiceField(
+ choices=[kind.value for kind in WatchCardKind],
+ help_text=(
+ "What the card is: 'behavior' for an event this variant did clearly more than the other variants "
+ "together, 'friction' for the same finding on an error or rage signal, 'metric' for a shortcut to "
+ "recordings around one of the experiment's own metric events. Metric cards claim nothing about how "
+ "the metric moved: that is the experiment results' answer."
+ ),
+ )
+ event = serializers.CharField(help_text="The event behind the card.")
+ variant = serializers.CharField(
+ help_text="The variant whose recordings these are: for comparison cards, the one that did the event more."
+ )
+ strength = serializers.ChoiceField(
+ choices=[strength.value for strength in DeltaStrength],
+ allow_null=True,
+ help_text=(
+ "How far apart this variant and the rest are, as a band rather than a number: 'only' when nobody in "
+ "the other variants did it at all among the people compared, then 'far_more', 'more' and "
+ "'slightly_more'. Read off the conservative end of the difference, so a card that clears the bar "
+ "only because the sample is large reports as slight. Null on metric cards, which compare nothing. "
+ "Present a band as a comparison ('far more common in test'), never convert it into a multiple."
+ ),
+ )
+ metric_name = serializers.CharField(
+ allow_null=True,
+ help_text="The metric whose event this card shortcuts to. Null outside metric cards.",
+ )
+ recording_count = serializers.IntegerField(
+ help_text=(
+ f"How many recordings the card carries, at most {MAX_CARD_RECORDINGS}. Every card is backed by "
+ "recordings that actually exist: a finding whose sessions were never recorded is dropped rather "
+ "than promised."
+ )
+ )
+ session_ids = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="The recordings themselves, most recent first, ready to hand to the recordings list as-is.",
+ )
+
+
+class ExperimentWatchArmSerializer(serializers.Serializer):
+ """One variant's compared population."""
+
+ key = serializers.CharField(help_text="The variant key.")
+ persons = serializers.IntegerField(
+ help_text=(
+ "Exposed people the comparison covered for this variant. People rather than sessions because a "
+ "variant can change how often the flag is evaluated again later, which moves a variant's session "
+ "count without anyone behaving differently. Each person is read from the first session the "
+ "comparison covers them in, so every variant gets the same amount of behavior per person."
+ )
+ )
+ sessions = serializers.IntegerField(
+ help_text=(
+ "Exposed sessions those people were seen in, which is more than the comparison reads: it says how "
+ "much recorded material sits behind the variant."
+ )
+ )
+
+
+class ExperimentSessionEventDeltaResponseSerializer(serializers.Serializer):
+ """The recordings worth watching for this experiment, grouped into cards.
+
+ Descriptive, never a result: cards say where behavior visibly differed and hand over the
+ recordings, while the experiment's results measure its metrics over the whole run window and
+ state the magnitudes. Nothing here says a variant is winning.
+ """
+
+ cards = ExperimentWatchCardSerializer(
+ many=True,
+ help_text=(
+ "The shelf, strongest comparison first, then metric shortcuts. Events the variants can't be told "
+ "apart on get no card at all rather than a weak one, so an empty shelf means no difference was big "
+ "enough to be sure of, not that nothing was measured. The experiment's own metric events never "
+ "appear as comparisons: see metric_events."
+ ),
+ )
+ arms = ExperimentWatchArmSerializer(
+ many=True,
+ help_text="Every variant's compared population, in the flag's variant order.",
+ )
+ multiple_variant_persons = serializers.IntegerField(
+ help_text=(
+ "People who saw more than one variant and were left out of every card. Always 0 when the experiment "
+ "attributes such users to the variant they saw first."
+ )
+ )
+ multiple_variant_handling = serializers.ChoiceField(
+ choices=[handling.value for handling in MultipleVariantHandling],
+ help_text=(
+ "How the experiment handles someone who saw more than one variant, followed here so the cards split "
+ "their people the same way the analysis does."
+ ),
+ )
+ metric_events = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "The experiment's own metric events, which never enter the behavior comparison. They are the events "
+ "it was built to move, so they would top the ranking on nearly every experiment, and the "
+ "experiment's results already say what happened to them with the statistics that go with a result. "
+ "They can appear as 'metric' shortcut cards, which claim nothing."
+ ),
+ )
+ date_from = serializers.DateTimeField(
+ help_text=(
+ f"Start of what was actually compared. The requested window is the experiment's run window clamped "
+ f"to its most recent {MAX_DELTA_SCAN_DAYS} days ({MAX_FALLBACK_DELTA_SCAN_DAYS} when sessions are "
+ "matched on the stamped flag property, which no event name can prune a scan on), but a busy "
+ "experiment reaches the session ceiling long before that, and this reports where the compared "
+ "sessions really begin - often hours rather than days back. Display this, not the experiment's own "
+ "dates."
+ )
+ )
+ date_to = serializers.DateTimeField(
+ help_text="End of what was compared: the experiment's end date, or now while it runs."
+ )
+ filter_test_accounts = serializers.BooleanField(
+ help_text=(
+ "Whether the project's test-account filters were applied, following the experiment's exposure "
+ "criteria, the same rule the experiment's recordings list uses."
+ )
+ )
+ used_exposure_fallback = serializers.BooleanField(
+ help_text=(
+ "True when the compared sessions were matched on the stamped $feature/<flag key> event property "
+ "instead of the exposure event, because the default exposure event has only ever been captured "
+ "server-side and can never match a session. The sessions then mean 'the flag was active in this "
+ "session', and the variant comes from the flag's value on each event, so a returning user can be "
+ "counted under a variant they were re-bucketed into later."
+ )
+ )
+ sessions_truncated = serializers.BooleanField(
+ help_text=(
+ "True when the experiment had more exposed sessions in the requested window than one comparison "
+ "covers, so the most recent ones were used and date_from is later than the experiment's own window. "
+ "Every variant is still covered over the same stretch of time."
+ )
+ )
+ events_truncated = serializers.BooleanField(
+ help_text=(
+ "True when the project has more distinct event names in the window than one comparison can rank, so "
+ "some were never considered."
+ )
+ )
+ min_arm_persons = serializers.IntegerField(
+ help_text=(
+ "How many exposed people a variant needs before it can be compared at all. Below it a variant's "
+ "cards would be noise whatever the evidence bar allows."
+ )
+ )
+ too_early = serializers.BooleanField(
+ help_text=(
+ "True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and "
+ "cards is empty. Say 'too early to compare' and show the arms' counts; an empty shelf presented "
+ "without this would read as 'the variants behaved identically'."
+ )
+ )
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index f5984977ae64..fedef80b787b 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -10,6 +10,7 @@ This will be refactored incrementally in subsequent PRs to match the product arc
import json
import asyncio
+import logging
from typing import Any, Literal, cast
from django.conf import settings
@@ -34,7 +35,7 @@ from posthog.models.activity_logging.activity_page import ActivityLogPaginatedRe
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.permissions import is_service_auth
+from posthog.permissions import is_service_auth, posthog_feature_flag_enabled
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
@@ -42,6 +43,8 @@ from posthog.rate_limit import (
SessionBucketsSustainedRateThrottle,
SessionContextsBurstRateThrottle,
SessionContextsSustainedRateThrottle,
+ SessionEventDeltasBurstRateThrottle,
+ SessionEventDeltasSustainedRateThrottle,
)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControl
@@ -79,6 +82,8 @@ from products.experiments.backend.presentation.serializers import (
ExperimentSessionContextResponseSerializer,
ExperimentSessionContextsRequestSerializer,
ExperimentSessionContextsResponseSerializer,
+ ExperimentSessionEventDeltaRequestSerializer,
+ ExperimentSessionEventDeltaResponseSerializer,
ExperimentWriteSerializer,
RecalculateMetricsRequestSerializer,
RunningTimeCalculationInputSerializer,
@@ -109,6 +114,13 @@ from products.experiments.backend.session_buckets import (
get_experiment_session_bucket,
)
from products.experiments.backend.session_context import get_session_experiment_context, get_session_experiment_contexts
+from products.experiments.backend.session_event_deltas import (
+ EXPERIMENT_BEHAVIOR_COMPARISON_FLAG,
+ SessionEventDeltasUnavailable,
+ all_card_session_ids,
+ finalize_watch_cards,
+ get_experiment_session_event_deltas,
+)
from products.experiments.backend.temporal.models import (
ExperimentMetricsRecalculationWorkflowInputs as MetricsRecalcInputs,
)
@@ -116,6 +128,7 @@ from products.feature_flags.backend.models.evaluation_context import FeatureFlag
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.tasks.backend.facade import api as tasks_facade
+logger = logging.getLogger(__name__)
tracer = trace.get_tracer(__name__)
# Heavy JSON columns the list view never renders. Deferred for the list action so large
@@ -1490,6 +1503,82 @@ class EnterpriseExperimentsViewSet(
)
return Response(ExperimentSessionBucketResponseSerializer(result).data)
+ @validated_request(
+ request_serializer=ExperimentSessionEventDeltaRequestSerializer,
+ responses={200: OpenApiResponse(response=ExperimentSessionEventDeltaResponseSerializer)},
+ )
+ @action(
+ methods=["POST"],
+ detail=True,
+ url_path="session_event_deltas",
+ required_scopes=["experiment:read", "session_recording:read"],
+ # The heaviest read in this family: it compares every event name in the window, so unlike
+ # the bucket scan there is no event-name predicate for ClickHouse to prune on.
+ throttle_classes=[SessionEventDeltasBurstRateThrottle, SessionEventDeltasSustainedRateThrottle],
+ )
+ def session_event_deltas(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ """The recordings worth watching for this experiment, grouped into cards.
+
+ Each card is one sentence and the recordings that back it: an event one variant did clearly
+ more than the others, an error signal concentrated in one variant, or a shortcut to a
+ metric event happening on screen. Every card's count is a count of recordings that actually
+ exist, so handing its session ids to the recordings list can't come back empty. POST to
+ take the same throttle and cache posture as the other reads in this family rather than
+ because it carries a body: it takes no parameters, and it only reads.
+
+ It reports no effect size. The experiment's own metric events never enter the comparison,
+ and cards carry a direction and a band rather than a rate, a ratio or a person count: the
+ experiment's results already state magnitudes, computed per person over the whole run
+ window, and this reads one session per person over a clamped one. Two numbers for the same
+ event would read as a contradiction, so this surface states none.
+ """
+ experiment: Experiment = self.get_object()
+
+ if not self._session_event_deltas_enabled():
+ raise NotFound()
+
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Comparing an experiment's session behavior requires session replay access.")
+
+ try:
+ result = get_experiment_session_event_deltas(
+ team=self.team,
+ # user threads through to the HogQL queries: exposure criteria can filter on
+ # arbitrary properties, which must respect the viewer's property-level access
+ # control.
+ user=cast(User, request.user),
+ experiment=experiment,
+ )
+ except SessionEventDeltasUnavailable as error:
+ raise ValidationError(str(error))
+
+ # Applied to the computed shelf rather than inside the scan, as the session buckets do it:
+ # the shelf is cached across viewers sharing a restriction profile, so filtering on read is
+ # what keeps one viewer's entry from leaking another's denied recordings, and a revocation
+ # lands even while an entry is warm. The resource-level check above grants the replay
+ # product, not every recording in it — without this a viewer denied one recording could
+ # still read its id, the variant it was in, and an event it contains.
+ result = finalize_watch_cards(
+ result,
+ _accessible_session_ids(request, self.user_access_control, self.team, all_card_session_ids(result)),
+ )
+ return Response(ExperimentSessionEventDeltaResponseSerializer(result).data)
+
+ def _session_event_deltas_enabled(self) -> bool:
+ # Scoped to the experiment's organization rather than the caller's current one: a user in
+ # several orgs could otherwise switch their current org to a flagged-in one and read an
+ # experiment in an org that is not.
+ try:
+ return posthog_feature_flag_enabled(
+ EXPERIMENT_BEHAVIOR_COMPARISON_FLAG,
+ str(cast(User, self.request.user).distinct_id),
+ organization_id=self.organization_id,
+ team_id=self.team.id,
+ )
+ except Exception:
+ logger.warning("Failed to evaluate the experiment behavior comparison flag", exc_info=True)
+ return False
+
def _serialize_recalculation(recalc: ExperimentMetricsRecalculation, active_run: dict | None = None) -> dict:
results = get_run_results(recalc)
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index 834ee688fc11..af7ba84abd96 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -45,8 +45,6 @@ from datetime import datetime, timedelta
from enum import StrEnum
from typing import Optional
-from django.db import models
-from django.db.models.functions import Coalesce
from django.utils import timezone
from posthog.schema import EventsNode
@@ -57,7 +55,6 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.models import EventProperty
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
@@ -65,13 +62,8 @@ from posthog.utils import get_safe_cache, safe_cache_set
from products.access_control.backend.property_access_control import get_restricted_properties_for_team
from products.experiments.backend.hogql_queries.exposure_query_logic import (
- DEFAULT_EXPOSURE_EVENT,
- EXPERIMENT_EXPOSURE_EVENT,
- build_exposure_event_conditions,
- get_exposure_event_and_property,
get_test_accounts_filter,
normalize_to_exposure_criteria,
- resolve_default_exposure_event,
)
from products.experiments.backend.metric_events import (
MetricEventSource,
@@ -83,6 +75,7 @@ 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
logger = logging.getLogger(__name__)
@@ -263,40 +256,34 @@ def get_experiment_session_bucket(
requested = _resolve_requested_metrics(experiment, metric_uuids)
# The same rollout resolution the analysis queries apply, so the bucket population is counted
- # on the event the experiment's results actually read.
- default_exposure_event = resolve_default_exposure_event(team, experiment.start_date)
- exposure_event, _ = get_exposure_event_and_property(
- experiment.feature_flag.key, experiment.exposure_criteria, default_exposure_event=default_exposure_event
- )
-
- # One EventProperty read covers both linkability decisions — whether the exposure event can
- # match sessions at all, and which metrics can. The verdict must be the endpoint's own:
- # callers other than the tab (the API, MCP tools) have no reason to know the lookup exists,
- # and an empty bucket that's really an unlinkable event would read as "no sessions did this".
- # An action-based exposure has no single event name to look up, so it fails open, the same
- # posture action metric sources get.
- # Collected per source, not per metric: `_source_event_names` is all-or-nothing, so a funnel
- # with an action step among its named ones would contribute none of its event names and the
- # boundary check below would pass on a name the lookup never asked about.
- lookup_names: set[str] = {exposure_event} if exposure_event is not None else set()
+ # on the event the experiment's results actually read. The linkability verdict must be the
+ # endpoint's own: callers other than the tab (the API, MCP tools) have no reason to know the
+ # lookup exists, and an empty bucket that's really an unlinkable event would read as "no
+ # sessions did this".
+ #
+ # Event names collected per source, not per metric: `_source_event_names` is all-or-nothing, so
+ # a funnel with an action step among its named ones would contribute none of its event names and
+ # the boundary check below would pass on a name the lookup never asked about.
+ lookup_names: set[str] = set()
for metric in requested:
lookup_names |= _concrete_event_names(metric)
- never_linked = _never_session_linked_events(team, lookup_names)
- # Both default exposure events mean "this user was enrolled via the flag", which the stamped
- # flag property implies too, so either can take the fallback.
- use_exposure_fallback = (
- exposure_event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT) and exposure_event in never_linked
- )
- if exposure_event in never_linked and not use_exposure_fallback:
- # Only the default events have a stand-in. Custom criteria assert that something specific
- # happened, which the stamped flag property doesn't imply, so falling back would answer
- # over "the flag was active in this session" — a wider population than the criteria name.
+ exposure = resolve_session_exposure(team, experiment, event_names=frozenset(lookup_names))
+ if exposure.is_unmatchable:
raise SessionBucketUnavailable(CUSTOM_EXPOSURE_UNLINKABLE_REASON)
- considered, excluded = _partition_metrics(requested, bucket, never_linked)
+ considered, excluded = _partition_metrics(requested, bucket, exposure.never_linked)
cache_key = _cache_key(
- team, user, experiment, bucket, considered, variant, window_start, window_end, limit, default_exposure_event
+ team,
+ user,
+ experiment,
+ bucket,
+ considered,
+ variant,
+ window_start,
+ window_end,
+ limit,
+ exposure.default_exposure_event,
)
cached = get_safe_cache(cache_key)
if cached is not None:
@@ -312,8 +299,7 @@ def get_experiment_session_bucket(
window_start=window_start,
window_end=window_end,
limit=limit,
- use_exposure_fallback=use_exposure_fallback,
- default_exposure_event=default_exposure_event,
+ exposure=exposure,
)
result = SessionBucketScan(
candidate_session_ids=candidate_session_ids,
@@ -326,7 +312,7 @@ def get_experiment_session_bucket(
date_from=window_start,
date_to=window_end,
filter_test_accounts=filter_test_accounts,
- used_exposure_fallback=use_exposure_fallback,
+ used_exposure_fallback=exposure.used_fallback,
)
safe_cache_set(cache_key, result, timeout=SESSION_BUCKET_CACHE_TTL)
return result
@@ -383,7 +369,7 @@ def _resolve_requested_metrics(experiment: Experiment, metric_uuids: list[str])
def _partition_metrics(
- requested: list[MetricEventSource], bucket: SessionBucket, never_linked: set[str]
+ requested: list[MetricEventSource], bucket: SessionBucket, never_linked: frozenset[str]
) -> tuple[list[MetricEventSource], list[ExcludedBucketMetric]]:
"""Split the requested metrics into the ones the bucket is computed over and the ones that
can't be matched to a recording at all, with the reason.
@@ -430,7 +416,7 @@ def _partition_metrics(
return considered, excluded
-def _exclusion_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:
+def _exclusion_reason(metric: MetricEventSource, never_linked: frozenset[str]) -> Optional[str]:
if not metric.session_linkable:
return DATA_WAREHOUSE_EXCLUSION_REASON
if any(
@@ -469,24 +455,6 @@ def _source_event_names(metric: MetricEventSource) -> Optional[set[str]]:
return names
-def _never_session_linked_events(team: Team, event_names: set[str]) -> set[str]:
- """Event names never ingested with a `$session_id` property — only ever captured
- server-side, so no recordings filter on them can match. The same `EventProperty` fact the
- taxonomy `seen_together` endpoint serves the tab, read directly so the verdict doesn't
- depend on the caller knowing to check."""
- if not event_names:
- return set()
- seen = (
- EventProperty.objects.alias(
- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
- )
- .filter(effective_project_id=team.project_id, event__in=sorted(event_names), property="$session_id")
- .values_list("event", flat=True)
- .distinct()
- )
- return event_names - set(seen)
-
-
def _metric_condition(metric: MetricEventSource, team: Team) -> ast.Expr:
"""Match expression for "any of this metric's events" — the OR over its sources, built on the
same matcher the analysis uses, so what counts as this metric's event can't diverge."""
@@ -505,7 +473,7 @@ def _funnel_completion_step(metric: MetricEventSource) -> MetricSource:
return steps[-1]
-def _funnel_completion_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:
+def _funnel_completion_reason(metric: MetricEventSource, never_linked: frozenset[str]) -> Optional[str]:
"""Why drop-off can't be asked of this funnel, or None when it can.
The whole-metric check in `_exclusion_reason` is too coarse here. It clears a funnel as long
@@ -549,41 +517,10 @@ def _query_bucket_sessions(
window_start: datetime,
window_end: datetime,
limit: int,
- use_exposure_fallback: bool,
- default_exposure_event: str,
+ exposure: SessionExposure,
) -> tuple[list[str], bool]:
- flag_key = experiment.feature_flag.key
- _event, variant_property = get_exposure_event_and_property(
- flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event
- )
- if use_exposure_fallback:
- variant_property = f"$feature/{flag_key}"
-
def exposure_condition() -> ast.Expr:
- # The exposure criteria resolved through the shared helpers — the single seam that keeps
- # this surface in sync with the analysis and with the player's session context. Rebuilt
- # per use site: the HogQL resolver annotates ast nodes in place, so one instance can't
- # appear in both the WHERE and the HAVING.
- variant_condition = ast.CompareOperation(
- op=ast.CompareOperationOp.In,
- left=ast.Call(name="toString", args=[ast.Field(chain=["properties", variant_property])]),
- right=ast.Constant(value=variant_keys),
- )
- if use_exposure_fallback:
- # The default exposure event has only ever been captured server-side, so it can't
- # match any session. posthog-js stamps `$feature/<flag_key>` on every client event
- # captured after flags load, so the stamped property stands in — the same fallback
- # the tab's own list uses. It means "the flag was active in this session", not "the
- # enrollment moment was captured": no event-name condition, and the variant is the
- # flag's value on each event rather than the exposure response.
- return variant_condition
- conditions = [
- *build_exposure_event_conditions(
- experiment.exposure_criteria, team, flag_key, default_exposure_event=default_exposure_event
- ),
- variant_condition,
- ]
- return ast.And(exprs=conditions) if len(conditions) > 1 else conditions[0]
+ return exposure.condition(variant_keys)
def metric_conditions() -> list[ast.Expr]:
return [_metric_condition(metric, team) for metric in considered]
diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.py
new file mode 100644
index 000000000000..eaa72299b820
--- /dev/null
+++ b/products/experiments/backend/session_event_deltas.py
@@ -0,0 +1,1128 @@
+"""Pick the recordings worth watching in one experiment's exposed sessions.
+
+The recordings tab can list an arm's sessions but says nothing about which of the thousands carry
+signal, so picking what to watch is sampling rather than targeting. This module answers that with
+watch cards: bounded groups of recordings, each one a sentence a reader can act on — "this arm did
+this event clearly more than the others, here are recordings of it happening".
+
+**Recordings are the deliverable.** A card's count is a count of watchable recordings, checked
+against replay existence before the card is returned; a finding that no recording can back is
+dropped, because a promise the playlist can't keep reads as the feature being broken. The event
+comparison underneath is the picking mechanism, not the product.
+
+**It reports no effect size, on purpose, and this is the constraint the file serves.** The results
+tab publishes one already, from a real statistics engine: per person, over the whole run window,
+with sample-ratio checks and credible intervals behind it. This reads one session per person over a
+window clamped to hours or days. Measured on a production experiment the two agreed on direction
+for every shared event and on no number at all — 7.5x there against 41x here for the same event —
+because the later sessions where people convert are outside what this reads. So the two rules that
+follow are not stylistic:
+
+ 1. The experiment's own metric events never enter the comparison. Those are the events it was
+ built to move, so they would top the ranking on nearly every experiment, and each row would
+ sit one tab away from a differently-computed answer to the same question. They come back only
+ as shortcuts — "recordings where this metric's event happened, per arm" — which claim nothing.
+ 2. Cards carry a direction and a band, never a rate, a ratio or a person count. Whatever we
+ called it, a precise number next to an event name is an effect size, and would be read
+ against the one the results tab computes.
+
+**Population.** The same session-scoped exposure evidence the tab's list and the session buckets
+use: a session containing an event that matches the experiment's exposure criteria and carries one
+of the flag's defined variants. That is not the analysis's population — a person whose SDK deduped
+later exposure events contributes only the session they were bucketed in. The comparison survives
+that because it is a *ratio* between arms selected by the same mechanism, which is exactly what an
+absolute per-session claim (the buckets) could not do.
+
+**One person, one session.** The sessions an arm is exposed in are not a fair denominator: a
+variant that stops re-evaluating the flag once a user has acted contributes fewer later sessions,
+and those missing sessions are the quiet ones. Measured on a production experiment this reached
+3.7x more exposed sessions in one arm off near-identical people, which pushed nine in ten event
+names to one side of the comparison: arithmetic reading as behavior. Counting each exposed person
+once fixes the denominator, and it makes the rows independent, which is what the ranking's noise
+test below assumes. It is not enough on its own, because the same imbalance is still in the
+numerator: on that experiment one arm's people averaged seven covered sessions each against the
+other's two, so they had seven chances to have done anything rather than two, and nine in ten event
+names still leaned one way. So a person is read from one session, the first the comparison covers
+them in, which is the same amount of behavior on both sides. A card's *recordings*, by contrast,
+come from any of the arm's covered sessions containing the event — the statistics need fairness,
+the watchlist needs the behavior on screen.
+
+**Ranking.** Each arm is compared against all the others pooled, so a five-arm experiment needs no
+pairing and costs the same one scan as two arms. Rates are compared on the log of their ratio, and
+an event earns a card only once the *conservative* end of that ratio is still a real difference.
+Without that test the list ranks rarity: on a production A/A pair — two arms of one experiment
+rendering identically — the raw ratio produced a full page of confident findings, every one of them
+noise, while the same data under this test produced nothing. The same conservative end picks the
+band a card is reported in, so a difference that only cleared the floor because the sample is large
+reports as slight, whatever its point estimate.
+
+**Cost.** The scan cannot prune by event name — the whole point is that it does not know which
+events matter yet. So the window is the only thing bounding it, which is why a first query resolves
+what the session ceiling actually covers and the scan is then clamped to that: on a busy project
+the ceiling is reached within hours of a nominally two-week window, and scanning the rest reads the
+project's whole recent history to find nothing. The follow-up queries that back cards with
+recordings filter by event name and by session id, so they prune on the events table's primary key
+and stay cheap. It is still the heaviest read on the tab, which is why the caller is expected to
+load it on demand.
+"""
+
+import json
+import math
+import hashlib
+from dataclasses import dataclass, replace
+from datetime import datetime, timedelta
+from enum import StrEnum
+from typing import Optional
+
+from django.utils import timezone
+
+from posthog.schema import EventsNode, MultipleVariantHandling
+
+from posthog.hogql import ast
+from posthog.hogql.database.database import Database
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+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.queries.session_replay_events import SessionReplayEvents
+from posthog.utils import get_safe_cache, safe_cache_set
+
+from products.access_control.backend.property_access_control import get_restricted_properties_for_team
+from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
+from products.experiments.backend.hogql_queries.exposure_query_logic import (
+ get_multiple_variant_handling_from_experiment,
+ get_test_accounts_filter,
+ normalize_to_exposure_criteria,
+)
+from products.experiments.backend.metric_events import (
+ MetricEventSource,
+ SharedHogQLDatabase,
+ build_source_condition,
+ resolve_metric_events,
+)
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.session_exposure import SessionExposure, resolve_session_exposure
+
+# 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
+# and has no such predicate, so the window is all that stands between it and the team's whole
+# recent history.
+MAX_DELTA_SCAN_DAYS = 14
+# Tighter again under the exposure fallback. The stamped flag property rides on every client
+# event, so not even the coverage query can prune by event name there, and the full window is
+# read three times per response before the session ceiling can clamp anything. Two days keeps
+# each of those reads inside the query timeout on the largest projects; `date_from` already
+# reports the window actually covered.
+MAX_FALLBACK_DELTA_SCAN_DAYS = 2
+# Ceiling on the exposed sessions one comparison covers, most recent first. Bounds the aggregation
+# state rather than the rows read, and because the cut is on recency across both arms at once, the
+# arms 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 arm) 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
+# How many behavior cards one response carries. The shelf is scanned, not scrolled, and a long tail
+# of near-identical differences is noise rather than depth.
+MAX_BEHAVIOR_CARDS = 8
+# How many of the experiment's metric events get shortcut cards, in the order its metrics are
+# defined, so the primary metric's event comes first. Per event there is one card per arm, so this
+# stays small to keep a five-arm experiment's shelf readable.
+MAX_METRIC_CARD_EVENTS = 2
+# Recording candidates fetched per card before replay existence is checked, and how many survive
+# onto the card. The margin absorbs sessions that were never recorded without a second round trip.
+MAX_CARD_RECORDING_CANDIDATES = 60
+MAX_CARD_RECORDINGS = 20
+# An event has to have been done by this many people in the arm it is more common in before it can
+# earn a card. The separation test below already drops rare events on its own; this only keeps the
+# candidate set from being mostly rows that can never pass it.
+MIN_SUPPORT_PERSONS = 10
+# Below this many exposed people an arm is noise to compare, whatever the floor above allows. With
+# fewer than two arms past it there is nothing to compare at all, which is reported as "too early"
+# rather than as an empty shelf that would read as "the variants behaved identically".
+MIN_ARM_PERSONS = 50
+# Laplace-style smoothing on both shares before they are divided. Keeps "none in one arm" finite and
+# pulls small counts toward no difference, so the ranking is not led by rare events.
+RATIO_SMOOTHING = 0.5
+# How many standard errors of separation a difference needs before it earns a card at all. This is a
+# ranking floor, not a significance claim, and it is deliberately past the conventional 1.96: one
+# comparison tests every event name in the project at once, so the loose threshold that reads as
+# "95% sure" for a single question is wrong by hundreds of tries here. On a production A/A pair the
+# 1.96 version still let a difference through, barely above the floor; at this width the same data
+# fell short of the floor and produced no cards at all.
+CONFIDENCE_Z = 2.58
+# ...and how big the conservative end of the ratio still has to be, in log space: about 1.35x. A
+# difference the reader cannot see while watching a recording is not worth a card telling them to.
+MIN_LOG_RATIO_LOWER_BOUND = 0.3
+# Where that conservative end earns a stronger word, in log space: about 3x and about 1.5x. Bands
+# rather than the number itself, for the reason in the module docstring — the number is the part
+# that reads as an effect size and collides with the one the results tab computes.
+FAR_MORE_LOG_RATIO = 1.1
+MORE_LOG_RATIO = 0.4
+# Per (team, experiment, window bucket, viewer restriction profile). The window moves with
+# wall-clock time on a running experiment, so the key it is built from is quantized to this same
+# interval — at any finer resolution the key would change faster than the entry expires and the
+# TTL would never apply, leaving the heaviest read on the tab uncached in practice.
+DELTA_CACHE_TTL = 15 * 60
+# Kept beside the scan rather than with the viewset's other constants so the flag and what it gates
+# can't drift.
+EXPERIMENT_BEHAVIOR_COMPARISON_FLAG = "experiment-behavior-comparison"
+
+# Events whose *name* carries no behavior, so a difference in how often people do them says nothing
+# about what they did. Page views and autocaptures are the interesting ones to leave out: they are
+# in almost every session in both arms, so they rank last anyway, but their names describe a
+# mechanism rather than an action. What replaces them is a page-level comparison, which needs the
+# project's path-cleaning rules and a second grouping key, so it is not this scan.
+UNCOMPARABLE_EVENTS = frozenset(
+ {
+ "$pageview",
+ "$pageleave",
+ "$autocapture",
+ "$web_vitals",
+ "$feature_flag_called",
+ "$experiment_exposure",
+ "$feature_enrollment_update",
+ "$identify",
+ "$groupidentify",
+ "$create_alias",
+ "$merge_dangerously",
+ "$set",
+ "$snapshot",
+ "$$heatmap",
+ "survey shown",
+ }
+)
+
+# Events whose card belongs on the friction shelf rather than the behavior one. Same pipeline and
+# the same evidence bar — the split is presentation: a reader triages "the new variant breaks
+# something" differently from "the new variant changes what people do".
+FRICTION_EVENTS = frozenset({"$exception", "$rageclick", "$dead_click"})
+
+# Distinct from session_buckets' CUSTOM_EXPOSURE_UNLINKABLE_REASON in both name and wording: the
+# bucket can't *match* such an event, this can't *compare* on it, and a reader hitting one of the two
+# endpoints should get the sentence that describes what they asked for.
+CUSTOM_EXPOSURE_UNCOMPARABLE_REASON = (
+ "This experiment's exposure event has only ever been captured server-side, where there is no session to "
+ "record, so no session can be compared."
+)
+
+
+class SessionEventDeltasUnavailable(Exception):
+ """The cards can't be computed for this experiment — a caller error, not a failure.
+ Raised instead of returning an empty shelf, so "we declined to compare" never reads as
+ "the arms behaved identically"."""
+
+
+class DeltaStrength(StrEnum):
+ """How far apart an arm and the rest are, conservatively, in bands rather than as a number."""
+
+ # Nobody in the other arms did it, among the people compared. A fact about the compared set
+ # rather than a ratio, and the one band that is exact.
+ ONLY = "only"
+ FAR_MORE = "far_more"
+ MORE = "more"
+ SLIGHTLY_MORE = "slightly_more"
+
+
+class WatchCardKind(StrEnum):
+ # An event this arm did clearly more than the other arms together.
+ BEHAVIOR = "behavior"
+ # Same evidence, but the event is an error/rage signal, so it reads as a defect lead.
+ FRICTION = "friction"
+ # A shortcut to recordings around one of the experiment's own metric events. No comparison
+ # claim: what happened to the metric is the results tab's answer.
+ METRIC = "metric"
+
+
+@dataclass(frozen=True)
+class ExperimentWatchCard:
+ """One group of recordings worth opening, and the one sentence that justifies it.
+
+ Deliberately no rate, no ratio and no person count: a precise number next to an event name is
+ an effect size, and the results tab publishes those for everything the experiment measures,
+ computed over a different window and a different unit. The only number here is how many
+ recordings the card can actually show.
+ """
+
+ kind: WatchCardKind
+ event: str
+ # The arm whose recordings these are — for comparison cards, the arm that did the event more.
+ variant: str
+ # None on metric cards: they are shortcuts, not comparisons.
+ strength: Optional[DeltaStrength]
+ # The metric whose event this card shortcuts to; None outside metric cards.
+ metric_name: Optional[str]
+ recording_count: int
+ session_ids: list[str]
+
+
+@dataclass(frozen=True)
+class ExperimentWatchArm:
+ """One arm's compared population: exposed people, and the sessions they were seen in."""
+
+ key: str
+ persons: int
+ sessions: int
+
+
+@dataclass(frozen=True)
+class ExperimentWatchResult:
+ cards: list[ExperimentWatchCard]
+ arms: list[ExperimentWatchArm]
+ multiple_variant_persons: int
+ multiple_variant_handling: str
+ metric_events: list[str]
+ date_from: datetime
+ date_to: datetime
+ filter_test_accounts: bool
+ used_exposure_fallback: bool
+ sessions_truncated: bool
+ events_truncated: bool
+ min_arm_persons: int
+ too_early: bool
+
+
+def all_card_session_ids(result: ExperimentWatchResult) -> list[str]:
+ """Every recording the shelf would hand out, deduped — what the caller runs its per-recording
+ access filter over."""
+ return sorted({session_id for card in result.cards for session_id in card.session_ids})
+
+
+def finalize_watch_cards(result: ExperimentWatchResult, accessible_session_ids: list[str]) -> ExperimentWatchResult:
+ """Cut every card down to the recordings this viewer may open, dropping the ones left with none.
+
+ Applied on read rather than inside the scan, for the same reason the session buckets do it: the
+ shelf is cached — and shared across viewers with the same property restrictions — so this cut
+ is what keeps one viewer's entry from leaking another's denied recordings, and it honors a
+ revocation that lands while an entry is still warm. A card that loses every recording is
+ dropped rather than shown greyed-out — the same rule the scan applies to sessions replay never
+ recorded, since either way there is nothing to watch behind it. `recording_count` is recomputed
+ so it keeps meaning "recordings this card can show you".
+ """
+ accessible = set(accessible_session_ids)
+ cards = []
+ for card in result.cards:
+ session_ids = [session_id for session_id in card.session_ids if session_id in accessible]
+ if session_ids:
+ cards.append(replace(card, recording_count=len(session_ids), session_ids=session_ids))
+ return replace(result, cards=cards)
+
+
+def get_experiment_session_event_deltas(team: Team, user: User, experiment: Experiment) -> ExperimentWatchResult:
+ """The recordings worth watching for this experiment, grouped into cards.
+
+ The caller passes the result through `finalize_watch_cards` with the recordings this viewer may
+ open, which is what the cached shelf is cut down to before it is returned.
+
+ `user` is the viewer: exposure criteria can filter on arbitrary event properties, so the
+ queries run under that user's property-level access control, as the experiment query runners
+ do.
+
+ Raises SessionEventDeltasUnavailable when nothing can be compared at all — an experiment that
+ never launched, fewer than two variants, or an exposure event that can never match a session.
+ """
+ # Exposure criteria over the events table is experiments' own logic and cost, so it bills to
+ # experiments rather than to the tab it renders on.
+ tag_queries(product=Product.EXPERIMENTS, feature=Feature.QUERY, team_id=team.pk)
+
+ if experiment.start_date is None:
+ raise SessionEventDeltasUnavailable("This experiment hasn't launched, so it has no exposed sessions yet.")
+
+ variant_keys = [variant["key"] for variant in experiment.feature_flag.variants or []]
+ if len(variant_keys) < 2:
+ raise SessionEventDeltasUnavailable("This experiment's feature flag defines fewer than two variants.")
+
+ window_end = experiment.end_date or timezone.now()
+ window_start = max(experiment.start_date, window_end - timedelta(days=MAX_DELTA_SCAN_DAYS))
+ criteria = normalize_to_exposure_criteria(experiment.exposure_criteria)
+ filter_test_accounts = bool(criteria.filterTestAccounts) if criteria else False
+
+ # Resolved once for the whole response, because each call reads the experiment's saved-metric
+ # join again.
+ metrics = resolve_metric_events(experiment)
+ metric_event_names = _metric_event_names(metrics)
+ # The same rollout resolution the analysis queries and the session buckets apply, so the
+ # compared population is the one the experiment's own results count.
+ exposure = resolve_session_exposure(team, experiment, event_names=frozenset(metric_event_names))
+ if exposure.is_unmatchable:
+ raise SessionEventDeltasUnavailable(CUSTOM_EXPOSURE_UNCOMPARABLE_REASON)
+ if exposure.used_fallback:
+ window_start = max(window_start, window_end - timedelta(days=MAX_FALLBACK_DELTA_SCAN_DAYS))
+
+ # The experiment's own metric events never enter the comparison — the module docstring's first
+ # rule. They reappear below as shortcut cards, which claim nothing the results tab also claims.
+ excluded_events = sorted(
+ UNCOMPARABLE_EVENTS
+ | metric_event_names
+ | ({exposure.exposure_event} if exposure.exposure_event is not None else set())
+ )
+ multiple_variant_handling = get_multiple_variant_handling_from_experiment(experiment.exposure_criteria)
+
+ cache_key = _cache_key(team, user, experiment, window_start, window_end, exposure.default_exposure_event)
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+
+ modifiers = create_default_modifiers_for_team(team)
+ setup = _QuerySetup(
+ team=team,
+ user=user,
+ experiment=experiment,
+ variant_keys=variant_keys,
+ exposure=exposure,
+ window_end=window_end,
+ shared_hogql=SharedHogQLDatabase(
+ # Postgres foreign-key lazy joins are the most expensive part of building the virtual
+ # database and these queries only read events and replay summaries.
+ database=Database.create_for(team=team, user=user, modifiers=modifiers, build_postgres_foreign_keys=False),
+ modifiers=modifiers,
+ ),
+ )
+
+ scan = _query_event_deltas(
+ setup,
+ multiple_variant_handling=multiple_variant_handling,
+ excluded_events=excluded_events,
+ window_start=window_start,
+ )
+
+ arms = [
+ ExperimentWatchArm(key=key, persons=scan.persons.get(("", key), 0), sessions=scan.sessions.get(key, 0))
+ for key in variant_keys
+ ]
+ qualified_arms = [arm.key for arm in arms if arm.persons >= MIN_ARM_PERSONS]
+ too_early = len(qualified_arms) < 2
+
+ candidates: list[ExperimentWatchCard] = []
+ metric_nodes: dict[str, list[EventsNode]] = {}
+ if not too_early:
+ candidates = _pick_behavior_cards(scan, arm_keys=qualified_arms)
+ metric_cards, metric_nodes = _metric_card_candidates(
+ metrics, arm_keys=qualified_arms, never_linked=exposure.never_linked
+ )
+ candidates += metric_cards
+
+ cards: list[ExperimentWatchCard] = []
+ if candidates:
+ recordings = _recordings_for_cards(
+ setup,
+ wanted=[(candidate.event, candidate.variant) for candidate in candidates],
+ covered_from=scan.covered_from,
+ metric_nodes=metric_nodes,
+ )
+ for candidate in candidates:
+ session_ids = recordings.get((candidate.event, candidate.variant), [])
+ # A card that can't show a single recording is dropped, not rendered greyed-out: the
+ # deliverable is what can be watched, and replay sampling or retention already ate
+ # these sessions.
+ if session_ids:
+ cards.append(replace(candidate, recording_count=len(session_ids), session_ids=session_ids))
+
+ result = ExperimentWatchResult(
+ cards=cards,
+ arms=arms,
+ multiple_variant_persons=scan.persons.get(("", MULTIPLE_VARIANT_KEY), 0),
+ multiple_variant_handling=multiple_variant_handling.value,
+ # Reported without the ones already left out for describing a mechanism: a reader pointed
+ # at the results tab for `$pageview` would go looking for a row that was never coming
+ # either way.
+ metric_events=sorted(metric_event_names - UNCOMPARABLE_EVENTS),
+ date_from=scan.covered_from,
+ date_to=window_end,
+ filter_test_accounts=filter_test_accounts,
+ used_exposure_fallback=exposure.used_fallback,
+ sessions_truncated=scan.sessions_truncated,
+ events_truncated=scan.events_truncated,
+ min_arm_persons=MIN_ARM_PERSONS,
+ too_early=too_early,
+ )
+ safe_cache_set(cache_key, result, timeout=DELTA_CACHE_TTL)
+ return result
+
+
+@dataclass(frozen=True)
+class SessionEventDeltaScan:
+ """What the scan returned: per (event name, variant) the number of that arm's exposed people
+ who did it in their first covered session, plus each arm's own totals under the empty event
+ name."""
+
+ persons: dict[tuple[str, str], int]
+ sessions: dict[str, int]
+ events_truncated: bool
+ sessions_truncated: bool
+ # The start of what was actually compared, which is later than the requested window whenever the
+ # session ceiling bit. Carried here rather than recomputed by the caller: it is a property of
+ # the scan, and reporting the requested window instead would claim coverage that never happened.
+ covered_from: datetime
+
+
+@dataclass(frozen=True)
+class _QuerySetup:
+ """Everything the scan and the recordings query share: the experiment's exposure semantics and
+ one HogQL database. The ast builders are methods so every use site gets a fresh tree — the
+ HogQL resolver annotates nodes in place, so one instance can't appear in two clauses."""
+
+ team: Team
+ user: User
+ experiment: Experiment
+ variant_keys: list[str]
+ exposure: SessionExposure
+ window_end: datetime
+ shared_hogql: SharedHogQLDatabase
+
+ def exposure_condition(self) -> ast.Expr:
+ # Every defined variant, not only the ones being compared: the multi-variant check has to
+ # see a person who also saw a third arm, or that person reads as single-variant and is
+ # attributed to an arm they only half belong to.
+ return self.exposure.condition(self.variant_keys)
+
+ def variant_value(self) -> ast.Expr:
+ return self.exposure.variant_value()
+
+ def window_conditions(self, start: datetime) -> list[ast.Expr]:
+ return [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=start),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=self.window_end),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.NotEq, left=ast.Field(chain=["$session_id"]), right=ast.Constant(value="")
+ ),
+ *get_test_accounts_filter(self.team, self.experiment.exposure_criteria),
+ ]
+
+ def exposed_sessions(self, start: datetime, *, of: str) -> ast.SelectQuery:
+ # The exposed sessions, most recent first. Its only job is to bound what the scan
+ # aggregates: without it the scan would hold one row per person in the whole window rather
+ # than per exposed person.
+ #
+ # On the default path the exposure condition carries an event name, so ClickHouse prunes
+ # this on the events table's primary key. Under the exposure fallback there is no event
+ # name to prune on, only the stamped flag property, so it reads the window instead. That is
+ # the same posture the session buckets take on their own fallback path, but it lands harder
+ # here because three queries in one response each resolve this subquery.
+ #
+ # `of` picks the one column each use site can take: the ceiling has to be applied before
+ # either is read, and an IN subquery may only return one.
+ last_seen = ast.Alias(alias="last_seen", expr=ast.Call(name="max", args=[ast.Field(chain=["timestamp"])]))
+ return ast.SelectQuery(
+ select=[last_seen if of == "last_seen" else ast.Field(chain=[of])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(exprs=[*self.window_conditions(start), self.exposure_condition()]),
+ group_by=[ast.Field(chain=["$session_id"])],
+ order_by=[
+ ast.OrderExpr(expr=ast.Call(name="max", args=[ast.Field(chain=["timestamp"])]), order="DESC"),
+ ],
+ limit=ast.Constant(value=MAX_DELTA_SCAN_SESSIONS),
+ )
+
+ def run(self, query: ast.SelectQuery) -> list[tuple]:
+ response = execute_hogql_query(
+ query,
+ team=self.team,
+ user=self.user,
+ context=self.shared_hogql.fresh_context(self.team, self.user),
+ modifiers=self.shared_hogql.modifiers,
+ )
+ return list(response.results or [])
+
+
+def _cache_key(
+ team: Team,
+ user: User,
+ experiment: Experiment,
+ window_start: datetime,
+ window_end: datetime,
+ default_exposure_event: str,
+) -> str:
+ # The version segment must be bumped whenever ExperimentWatchResult or SessionEventDeltaScan
+ # changes shape: entries are pickled, so a deploy would otherwise restore instances missing the
+ # new fields.
+ spec = json.dumps(
+ [
+ # Which event the default exposure resolved to. The $experiment_exposure rollout can
+ # flip under a team, and cards computed on the other event are a different population.
+ default_exposure_event,
+ # The window moves with wall-clock time on a running experiment, so it is quantized to
+ # the cache's own TTL rather than to the minute: at minute resolution the key changes
+ # every minute and the entry it would have reused is still warm, so every reload pays
+ # for a full scan. The cost of the coarser bucket is that an answer can be one TTL
+ # stale, which is what the TTL already promised.
+ int(window_start.timestamp()) // DELTA_CACHE_TTL,
+ int(window_end.timestamp()) // DELTA_CACHE_TTL,
+ # The experiment's metrics decide what is excluded from the comparison and what gets a
+ # shortcut card, its exposure criteria decide who is compared and how someone who saw
+ # two variants is split, and the flag's variants decide the arms. All of them are
+ # editable while an entry is warm, and none can be re-applied on read, so an edit has
+ # to miss the cache rather than be served the answer to the previous configuration.
+ experiment.updated_at.isoformat(),
+ experiment.feature_flag.updated_at.isoformat() if experiment.feature_flag.updated_at else None,
+ # A saved metric is editable without touching the experiment row, and its events decide
+ # exclusions and shortcut cards the same way an inline metric's do.
+ sorted(updated.isoformat() for updated in experiment.saved_metrics.values_list("updated_at", flat=True)),
+ # Property restrictions are compiled into the SQL, so a restriction change has to miss
+ # the cache rather than be re-applied on read.
+ sorted(get_restricted_properties_for_team(user=user, team=team)),
+ ]
+ )
+ digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
+ # Keyed by the viewer's restriction profile, not by the viewer: the property restrictions in
+ # the digest are the only viewer-dependent input to the scan, and per-recording access is
+ # applied on read. One viewer's scan then serves every viewer whose restrictions match, which
+ # on the heaviest read in this family is the difference between paying it once per team per
+ # TTL and once per viewer.
+ return f"experiment_session_event_deltas_v4_{team.pk}_{experiment.pk}_{digest}"
+
+
+def _metric_event_names(metrics: list[MetricEventSource]) -> set[str]:
+ """Every named event this experiment's metrics count.
+
+ These are excluded from the comparison and shortcut instead. Sources with no single event name
+ (actions, all-events nodes) are skipped — they can match client-captured events, so their
+ identity can't be decided from a name.
+ """
+ return {
+ source.node.event
+ for metric in metrics
+ for source in metric.sources
+ if isinstance(source.node, EventsNode) and source.node.event
+ }
+
+
+def _query_event_deltas(
+ setup: _QuerySetup,
+ *,
+ multiple_variant_handling: MultipleVariantHandling,
+ excluded_events: list[str],
+ window_start: datetime,
+) -> SessionEventDeltaScan:
+ # What the session ceiling actually covers. Cheap next to the scan — it prunes on the exposure
+ # event name — and it is what lets the scan skip the stretch of the window where none of the
+ # covered sessions live. On a busy project that is most of the window.
+ coverage = setup.run(
+ ast.SelectQuery(
+ select=[
+ ast.Call(name="min", args=[ast.Field(chain=["last_seen"])]),
+ ast.Call(name="count", args=[]),
+ ],
+ select_from=ast.JoinExpr(table=setup.exposed_sessions(window_start, of="last_seen")),
+ )
+ )
+ covered_sessions = int(coverage[0][1]) if coverage else 0
+ if not covered_sessions:
+ return SessionEventDeltaScan(
+ persons={}, sessions={}, events_truncated=False, sessions_truncated=False, covered_from=window_start
+ )
+ oldest_covered: datetime = coverage[0][0]
+ covered_from = max(window_start, oldest_covered - timedelta(hours=MAX_SESSION_DURATION_HOURS))
+
+ # One row per (person, exposed session): when it began, which arm its exposures carried, and
+ # which event names it contains. The uncomparable names are dropped here rather than in the
+ # WHERE so a session whose only events are exposures still produces a row and its person still
+ # counts toward their arm's total.
+ session_rows = ast.SelectQuery(
+ select=[
+ ast.Field(chain=["person_id"]),
+ ast.Alias(alias="started", expr=ast.Call(name="min", args=[ast.Field(chain=["timestamp"])])),
+ ast.Alias(
+ alias="first_exposure",
+ expr=ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), setup.exposure_condition()]),
+ ),
+ ast.Alias(
+ alias="session_variant",
+ expr=ast.Call(
+ name="argMinIf",
+ args=[setup.variant_value(), ast.Field(chain=["timestamp"]), setup.exposure_condition()],
+ ),
+ ),
+ ast.Alias(
+ alias="session_variants",
+ expr=ast.Call(name="countDistinctIf", args=[setup.variant_value(), setup.exposure_condition()]),
+ ),
+ ast.Alias(
+ alias="event_names",
+ expr=ast.Call(
+ name="groupUniqArrayIf",
+ args=[
+ ast.Field(chain=["event"]),
+ ast.And(
+ exprs=[
+ ast.Call(name="notEmpty", args=[ast.Field(chain=["event"])]),
+ ast.Call(
+ name="not",
+ args=[
+ ast.Call(
+ name="has",
+ args=[
+ ast.Constant(value=excluded_events),
+ ast.Field(chain=["event"]),
+ ],
+ )
+ ],
+ ),
+ ]
+ ),
+ ],
+ ),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ *setup.window_conditions(covered_from),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["$session_id"]),
+ # Re-resolved over the clamped window rather than passed in as ids: the ceiling
+ # picks the same sessions either way, and 20,000 ids inlined into the SQL is a
+ # megabyte of query text.
+ right=setup.exposed_sessions(covered_from, of="$session_id"),
+ ),
+ ]
+ ),
+ group_by=[ast.Field(chain=["person_id"]), ast.Field(chain=["$session_id"])],
+ )
+
+ # A (person, session) group can carry no exposure at all: server-side events reuse a client
+ # session's `$session_id` under their own person, so a covered session can hold a second
+ # person who was never exposed in it. Such a group's `session_variant` is NULL and its
+ # `first_exposure` is the epoch default, and the variant selections below stay correct only
+ # because ClickHouse aggregates skip NULL arguments — countDistinct can't count the NULL toward
+ # "saw two variants", and argMin can't let the epoch-timestamped NULL win. Wrapping these
+ # values in coalesce/assumeNotNull would silently misattribute every person who shares a
+ # session. The person's behavior and session count get no such implicit protection — their
+ # inputs are non-null even in an unexposed group — so both are conditioned on the group
+ # carrying an exposure explicitly, in `person_rows` below.
+ if multiple_variant_handling == MultipleVariantHandling.FIRST_SEEN:
+ # Mirrors get_variant_selection_expr across the person's sessions rather than within one.
+ variant_expr: ast.Expr = ast.Call(
+ name="argMin", args=[ast.Field(chain=["session_variant"]), ast.Field(chain=["first_exposure"])]
+ )
+ else:
+ variant_expr = ast.Call(
+ name="if",
+ args=[
+ ast.Or(
+ exprs=[
+ # Two arms across their sessions, or two inside one of them. The second is
+ # not implied by the first: a session carrying both exposures can still be
+ # the person's only one.
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(name="countDistinct", args=[ast.Field(chain=["session_variant"])]),
+ right=ast.Constant(value=1),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(name="max", args=[ast.Field(chain=["session_variants"])]),
+ right=ast.Constant(value=1),
+ ),
+ ]
+ ),
+ ast.Constant(value=MULTIPLE_VARIANT_KEY),
+ ast.Call(name="any", args=[ast.Field(chain=["session_variant"])]),
+ ],
+ )
+
+ # One row per exposed person: which arm they saw, how many sessions of theirs the comparison
+ # covers, and what they did in the first of them. Only the first, because the arms don't
+ # necessarily get the same number of sessions per person — a variant that stops re-evaluating
+ # the flag once someone has acted contributes fewer later sessions, and a person seen in seven
+ # sessions has seven times the chance to have done anything than one seen in two. Measured on a
+ # production experiment that difference alone put nine in ten event names on the same side of
+ # the comparison; one session each removes it.
+ # Exposed sessions only, for both the count and the behavior read: a person can also appear in
+ # a covered session someone else was exposed in, and reading behavior from there would break
+ # "read from the first session *they* were exposed in" — their real exposed session's events
+ # silently replaced by whatever they did in a session the comparison never bucketed them by.
+ group_is_exposed = ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Field(chain=["session_variants"]),
+ right=ast.Constant(value=0),
+ )
+ person_rows = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="variant", expr=variant_expr),
+ ast.Alias(alias="session_count", expr=ast.Call(name="countIf", args=[group_is_exposed])),
+ ast.Alias(
+ alias="event_names",
+ expr=ast.Call(
+ name="argMinIf",
+ args=[ast.Field(chain=["event_names"]), ast.Field(chain=["started"]), group_is_exposed],
+ ),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=session_rows),
+ group_by=[ast.Field(chain=["person_id"])],
+ )
+
+ # The empty event name is the arm's own totals. They ride the same aggregation so the
+ # denominator can never be computed over a different set than the numerators — and `notEmpty`
+ # above guarantees no real event name collides with it.
+ query = ast.SelectQuery(
+ select=[
+ ast.Alias(
+ alias="event_name",
+ expr=ast.Call(
+ name="arrayJoin",
+ args=[
+ ast.Call(
+ name="arrayConcat",
+ args=[ast.Array(exprs=[ast.Constant(value="")]), ast.Field(chain=["event_names"])],
+ )
+ ],
+ ),
+ ),
+ ast.Field(chain=["variant"]),
+ ast.Alias(alias="persons", expr=ast.Call(name="count", args=[])),
+ ast.Alias(alias="sessions", expr=ast.Call(name="sum", args=[ast.Field(chain=["session_count"])])),
+ ],
+ select_from=ast.JoinExpr(table=person_rows),
+ # Every arm, not only the qualifying ones: the totals are what decide which arms qualify at
+ # all, and on a three-arm experiment a total over two arms could never reach the ceiling.
+ group_by=[ast.Field(chain=["event_name"]), ast.Field(chain=["variant"])],
+ # By name, not by count: every arm's rows for one event stay adjacent, so hitting the
+ # ceiling drops whole events instead of leaving an event with one arm's count and a silent
+ # zero for the others.
+ order_by=[
+ ast.OrderExpr(expr=ast.Field(chain=["event_name"]), order="ASC"),
+ ast.OrderExpr(expr=ast.Field(chain=["variant"]), order="ASC"),
+ ],
+ # One past the cap, so a result that lands exactly on it isn't read as cut short.
+ limit=ast.Constant(value=MAX_DELTA_EVENT_ROWS + 1),
+ )
+
+ rows = [(str(row[0]), str(row[1]), int(row[2]), int(row[3])) for row in setup.run(query)]
+ events_truncated = len(rows) > MAX_DELTA_EVENT_ROWS
+ if events_truncated:
+ # The ceiling can land between an event's arm rows, which would read as one arm never
+ # having done it. Dropping the last event name is exact rather than nearly right.
+ last_event = rows[-1][0]
+ rows = [row for row in rows if row[0] != last_event]
+
+ return SessionEventDeltaScan(
+ persons={(event_name, variant): persons for event_name, variant, persons, _sessions in rows},
+ sessions={variant: sessions for event_name, variant, _persons, sessions in rows if event_name == ""},
+ events_truncated=events_truncated,
+ sessions_truncated=covered_sessions >= MAX_DELTA_SCAN_SESSIONS,
+ covered_from=covered_from,
+ )
+
+
+def _separation(
+ *, baseline_count: int, target_count: int, baseline_persons: int, target_persons: int
+) -> tuple[float, float]:
+ """The smoothed ratio of the two populations' rates, and how much of it survives the noise.
+
+ The second number is the conservative end of the ratio in log space: the difference minus the
+ uncertainty in it, so an event two people did more of in one arm cannot outrank one hundreds
+ did, however lopsided the raw ratio looks. Zero means the populations are indistinguishable on
+ it.
+ """
+ baseline_share = (baseline_count + RATIO_SMOOTHING) / (baseline_persons + 1)
+ target_share = (target_count + RATIO_SMOOTHING) / (target_persons + 1)
+ ratio = target_share / baseline_share
+
+ # Standard error of the log of a ratio of two independent proportions. Independent is why the
+ # unit is the person: two sessions of one person are not, and treating them as such is what
+ # makes an A/A comparison look full of findings.
+ variance = (
+ 1 / (baseline_count + RATIO_SMOOTHING)
+ + 1 / (target_count + RATIO_SMOOTHING)
+ - 1 / (baseline_persons + 1)
+ - 1 / (target_persons + 1)
+ )
+ standard_error = math.sqrt(max(variance, 0.0))
+ return ratio, max(abs(math.log(ratio)) - CONFIDENCE_Z * standard_error, 0.0)
+
+
+def _strength(*, separation: float, baseline_count: int, target_count: int) -> DeltaStrength:
+ """Which band the difference falls in, read off the conservative end of it rather than the raw
+ one. A card that is only past the floor because the sample is large says "slightly", however
+ big the point estimate looks."""
+ if not baseline_count or not target_count:
+ return DeltaStrength.ONLY
+ if separation >= FAR_MORE_LOG_RATIO:
+ return DeltaStrength.FAR_MORE
+ if separation >= MORE_LOG_RATIO:
+ return DeltaStrength.MORE
+ return DeltaStrength.SLIGHTLY_MORE
+
+
+def _pick_behavior_cards(scan: SessionEventDeltaScan, *, arm_keys: list[str]) -> list[ExperimentWatchCard]:
+ """The events one arm did clearly more than the other arms pooled, strongest first.
+
+ One card per event at most, on the arm where it is most over-represented — an event five arms
+ share is nobody's finding, and an event one arm lacks shows up as the other arms' card. Pooling
+ the rest is what makes a five-arm experiment cost the same ranking as two; on two arms it *is*
+ the pairwise comparison.
+ """
+ arm_persons = {key: scan.persons.get(("", key), 0) for key in arm_keys}
+ total_persons = sum(arm_persons.values())
+ event_names = {event_name for event_name, _variant in scan.persons if event_name != ""}
+
+ picked: list[tuple[float, ExperimentWatchCard]] = []
+ for event_name in sorted(event_names):
+ counts = {key: scan.persons.get((event_name, key), 0) for key in arm_keys}
+ total_count = sum(counts.values())
+ best: Optional[tuple[float, ExperimentWatchCard]] = None
+ for key in arm_keys:
+ rest_persons = total_persons - arm_persons[key]
+ rest_count = total_count - counts[key]
+ if counts[key] < MIN_SUPPORT_PERSONS or not rest_persons:
+ continue
+ # Only where the arm over-indexes: the card's recordings live on the arm that did the
+ # event, and under-indexing is the same fact seen from the other arms' cards.
+ if counts[key] * rest_persons <= rest_count * arm_persons[key]:
+ continue
+ _ratio, separation = _separation(
+ baseline_count=rest_count,
+ target_count=counts[key],
+ baseline_persons=rest_persons,
+ target_persons=arm_persons[key],
+ )
+ if separation < MIN_LOG_RATIO_LOWER_BOUND:
+ continue
+ card = ExperimentWatchCard(
+ kind=WatchCardKind.FRICTION if event_name in FRICTION_EVENTS else WatchCardKind.BEHAVIOR,
+ event=event_name,
+ variant=key,
+ strength=_strength(separation=separation, baseline_count=rest_count, target_count=counts[key]),
+ metric_name=None,
+ recording_count=0,
+ session_ids=[],
+ )
+ if best is None or separation > best[0]:
+ best = (separation, card)
+ if best is not None:
+ picked.append(best)
+
+ picked.sort(key=lambda entry: (-entry[0], entry[1].event))
+ # Friction is capped by FRICTION_EVENTS instead, at one card per name, because it renders on
+ # its own shelf and is the first thing a reader triages. Sharing one budget would let a run of
+ # behavior findings push the only $exception card out of the response entirely.
+ behavior = [card for _separation_value, card in picked if card.kind == WatchCardKind.BEHAVIOR]
+ friction = [card for _separation_value, card in picked if card.kind == WatchCardKind.FRICTION]
+ return behavior[:MAX_BEHAVIOR_CARDS] + friction
+
+
+def _metric_card_candidates(
+ metrics: list[MetricEventSource], *, arm_keys: list[str], never_linked: frozenset[str]
+) -> tuple[list[ExperimentWatchCard], dict[str, list[EventsNode]]]:
+ """Shortcut cards to recordings around the experiment's own metric events, one per arm.
+
+ No strength and no comparison claim: what happened to the metric is the results tab's answer.
+ These cards only say "here is the metric's event happening on screen, in this arm". Events that
+ have only ever been captured server-side can't back a recording and are skipped outright.
+
+ Also returns each card event's source nodes from the metric whose name the card carries, so the
+ recordings lookup can honor that metric's property filters: the card is labeled with the
+ metric's name, and a recording of the event happening outside the metric would be mislabeled.
+ """
+ named: list[tuple[str, str]] = []
+ owner_by_event: dict[str, str] = {}
+ nodes_by_event: dict[str, list[EventsNode]] = {}
+ for metric in metrics:
+ for source in metric.sources:
+ node = source.node
+ if not isinstance(node, EventsNode) or not node.event:
+ continue
+ if node.event in UNCOMPARABLE_EVENTS or node.event in never_linked:
+ continue
+ if node.event not in owner_by_event:
+ owner_by_event[node.event] = metric.metric_uuid
+ nodes_by_event[node.event] = [node]
+ named.append((node.event, metric.metric_name))
+ elif owner_by_event[node.event] == metric.metric_uuid:
+ # Another source of the owning metric on the same event — a funnel can repeat an
+ # event across steps with different filters, and any of them counts as the metric.
+ nodes_by_event[node.event].append(node)
+
+ kept = named[:MAX_METRIC_CARD_EVENTS]
+ cards = [
+ ExperimentWatchCard(
+ kind=WatchCardKind.METRIC,
+ event=event,
+ variant=arm_key,
+ strength=None,
+ metric_name=metric_name,
+ recording_count=0,
+ session_ids=[],
+ )
+ for event, metric_name in kept
+ for arm_key in arm_keys
+ ]
+ return cards, {event: nodes_by_event[event] for event, _name in kept}
+
+
+def _recordings_for_cards(
+ setup: _QuerySetup,
+ *,
+ wanted: list[tuple[str, str]],
+ covered_from: datetime,
+ metric_nodes: Optional[dict[str, list[EventsNode]]] = None,
+) -> dict[tuple[str, str], list[str]]:
+ """Recent recorded sessions per (event, arm) pair, most recent first.
+
+ Unlike the scan this prunes on event names, so it reads a sliver of the window. Every candidate
+ then goes through replay's own existence check rather than being trusted because it was exposed:
+ replay sampling, retention and deletion mean most exposed sessions have nothing to play, and a
+ card is only as good as the recordings behind it.
+ """
+ wanted_events = sorted({event for event, _arm in wanted})
+ wanted_arms = sorted({arm for _event, arm in wanted})
+ # A metric card's event counts only where the metric's own property filters hold: the card
+ # carries the metric's name, so a recording of the event happening outside the metric would be
+ # mislabeled. An unfiltered source subsumes any filtered one on the same event, so an event
+ # with one stays on the plain name match.
+ filtered_nodes = {
+ event: nodes
+ for event, nodes in (metric_nodes or {}).items()
+ if event in wanted_events and all(node.properties or node.fixedProperties for node in nodes)
+ }
+ plain_events = [event for event in wanted_events if event not in filtered_nodes]
+
+ def card_event_match() -> ast.Expr:
+ # Rebuilt per use site, like the setup's own builders: the HogQL resolver annotates ast
+ # nodes in place, so one instance can't appear in two clauses of the same query.
+ conditions: list[ast.Expr] = []
+ if plain_events:
+ conditions.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=plain_events),
+ )
+ )
+ for nodes in filtered_nodes.values():
+ conditions.extend(build_source_condition(node, setup.team) for node in nodes)
+ if not conditions:
+ return ast.Constant(value=False)
+ return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]
+
+ wanted_event_rows = card_event_match()
+ if setup.exposure.used_fallback:
+ # The stamped flag property rides on the wanted events themselves, so their names are the
+ # whole predicate.
+ reachable_rows: ast.Expr = wanted_event_rows
+ else:
+ # The exposure condition itself rather than the name of the event it matches, because an
+ # action-based exposure config resolves to no single name: `get_exposure_event_and_property`
+ # returns None for one, since an action can match several events. An event-name list would
+ # then drop every exposure row, leaving each session with no variant and every card
+ # unbacked. The condition carries the action's own event predicates, so ClickHouse still
+ # prunes on the events table's primary key. Same shape as the session buckets' WHERE.
+ reachable_rows = ast.Or(exprs=[wanted_event_rows, setup.exposure_condition()])
+
+ session_rows = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="session_id", expr=ast.Field(chain=["$session_id"])),
+ ast.Alias(alias="last_seen", expr=ast.Call(name="max", args=[ast.Field(chain=["timestamp"])])),
+ ast.Alias(
+ alias="variant",
+ expr=ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(
+ name="countDistinctIf", args=[setup.variant_value(), setup.exposure_condition()]
+ ),
+ right=ast.Constant(value=1),
+ ),
+ ast.Constant(value=MULTIPLE_VARIANT_KEY),
+ ast.Call(name="anyIf", args=[setup.variant_value(), setup.exposure_condition()]),
+ ],
+ ),
+ ),
+ ast.Alias(
+ alias="events_present",
+ expr=ast.Call(
+ name="groupUniqArrayIf",
+ args=[ast.Field(chain=["event"]), card_event_match()],
+ ),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ *setup.window_conditions(covered_from),
+ reachable_rows,
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["$session_id"]),
+ right=setup.exposed_sessions(covered_from, of="$session_id"),
+ ),
+ ]
+ ),
+ group_by=[ast.Field(chain=["$session_id"])],
+ )
+
+ candidates_query = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="event_name", expr=ast.Call(name="arrayJoin", args=[ast.Field(chain=["events_present"])])),
+ ast.Field(chain=["variant"]),
+ ast.Field(chain=["session_id"]),
+ ],
+ select_from=ast.JoinExpr(table=session_rows),
+ # A session that saw more than one variant belongs to no card. The check is per session
+ # here while the scan makes it per person across all of theirs, so under `exclude` a card
+ # can carry a recording from someone the comparison itself set aside, and under
+ # `first_seen` one from a session the scan counted toward another arm. Same split as the
+ # module docstring's: the comparison needs a fair population, the watchlist needs the
+ # behavior on screen.
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.In, left=ast.Field(chain=["variant"]), right=ast.Constant(value=wanted_arms)
+ ),
+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["last_seen"]), order="DESC")],
+ limit_by=ast.LimitByExpr(
+ n=ast.Constant(value=MAX_CARD_RECORDING_CANDIDATES),
+ exprs=[ast.Field(chain=["event_name"]), ast.Field(chain=["variant"])],
+ ),
+ # Sized on what LIMIT BY can emit, not on the cards asked for. The arrayJoin produces every
+ # (wanted event, wanted arm) pair that occurs, which is more pairs than there are cards —
+ # a carded event also happens in the arms that didn't earn a card. LIMIT runs after LIMIT BY
+ # and cuts by recency across all of them, so a limit sized on the cards would drop a card's
+ # older recordings in favor of rows belonging to a pair nobody asked about, and the card
+ # would then be dropped as unbacked.
+ limit=ast.Constant(value=MAX_CARD_RECORDING_CANDIDATES * max(len(wanted_events) * len(wanted_arms), 1)),
+ )
+
+ # The query emits every (wanted event, wanted arm) pair that occurs — a carded event also
+ # happens in arms that earned no card — but only the pairs a card actually asked for go on to
+ # the replay existence check, which pays per id.
+ wanted_pairs = set(wanted)
+ candidates: dict[tuple[str, str], list[str]] = {}
+ for row in setup.run(candidates_query):
+ pair = (str(row[0]), str(row[1]))
+ if pair in wanted_pairs:
+ candidates.setdefault(pair, []).append(str(row[2]))
+
+ all_session_ids = sorted({session_id for ids in candidates.values() for session_id in ids})
+ if not all_session_ids:
+ return {}
+
+ # Replay's own existence check rather than a read of the replay summaries here: "a row exists"
+ # is not the same question as "this recording can be opened", and only that helper applies the
+ # team's retention period and the deleted flag. A card promising a recording that expired or was
+ # deleted is the one failure the whole shelf is built to avoid.
+ exists_by_id = SessionReplayEvents().batch_exists(all_session_ids, setup.team)
+ recorded = {session_id for session_id in all_session_ids if exists_by_id.get(session_id)}
+
+ return {
+ pair: [session_id for session_id in ids if session_id in recorded][:MAX_CARD_RECORDINGS]
+ for pair, ids in candidates.items()
+ }
diff --git a/products/experiments/backend/session_exposure.py b/products/experiments/backend/session_exposure.py
new file mode 100644
index 000000000000..71579e34f8d4
--- /dev/null
+++ b/products/experiments/backend/session_exposure.py
@@ -0,0 +1,146 @@
+"""How a session-scoped experiment surface reads exposure.
+
+The session buckets and the watch shelf both answer questions about "the sessions this experiment
+exposed someone in", and both have to mean the same thing by it: which event carries the exposure,
+which property carries the variant, and what to do when that event was only ever captured where
+there is no session to record. Resolved once here, because two surfaces disagreeing on the
+population would show up as one of them silently answering over a wider set of sessions than it
+names.
+"""
+
+from dataclasses import dataclass
+from typing import Optional
+
+from django.db import models
+from django.db.models.functions import Coalesce
+
+from posthog.hogql import ast
+
+from posthog.models import EventProperty
+from posthog.models.team.team import Team
+
+from products.experiments.backend.hogql_queries.exposure_query_logic import (
+ DEFAULT_EXPOSURE_EVENT,
+ EXPERIMENT_EXPOSURE_EVENT,
+ build_exposure_event_conditions,
+ get_exposure_event_and_property,
+ resolve_default_exposure_event,
+)
+from products.experiments.backend.models.experiment import Experiment
+
+
+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
+ no recordings filter on them can match and no session-scoped surface can see them.
+
+ The same `EventProperty` fact the taxonomy `seen_together` endpoint serves the tab, read directly
+ so the verdict doesn't depend on the caller knowing to check.
+ """
+ if not event_names:
+ return frozenset()
+ seen = (
+ EventProperty.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
+ )
+ .filter(effective_project_id=team.project_id, event__in=sorted(event_names), property="$session_id")
+ .values_list("event", flat=True)
+ .distinct()
+ )
+ return event_names - frozenset(seen)
+
+
+@dataclass(frozen=True)
+class SessionExposure:
+ """One experiment's exposure semantics, as a session-scoped surface has to read them."""
+
+ team: Team
+ experiment: Experiment
+ # What this experiment's default exposure resolves to under the $experiment_exposure rollout.
+ # Carried rather than re-resolved so every clause in one response agrees on the event, even if
+ # the flag flips mid-request.
+ default_exposure_event: str
+ # None when the criteria name an action: an action can match several events, so there is no
+ # single name to look up or to prune a query on.
+ exposure_event: Optional[str]
+ # Already resolved to the stand-in where the fallback applies, so use sites never re-derive it.
+ variant_property: str
+ # Of the names asked about, the ones never ingested with a `$session_id`.
+ never_linked: frozenset[str]
+ used_fallback: bool
+
+ @property
+ def is_unmatchable(self) -> bool:
+ """True when the exposure event can never match a session and nothing stands in for it, so
+ the surface has nothing to answer over.
+
+ Only the default events have a stand-in. Custom criteria assert that something specific
+ happened, which the stamped flag property doesn't imply, so falling back would answer over
+ "the flag was active in this session" — a wider population than the criteria name.
+ """
+ return self.exposure_event in self.never_linked and not self.used_fallback
+
+ def variant_value(self) -> ast.Expr:
+ return ast.Call(name="toString", args=[ast.Field(chain=["properties", self.variant_property])])
+
+ def condition(self, variant_keys: list[str]) -> ast.Expr:
+ """Match expression for "this session exposed someone in one of these arms".
+
+ The exposure criteria resolved through the shared helpers — the single seam that keeps these
+ surfaces in sync with the analysis and with the player's session context. Rebuilt per use
+ site: the HogQL resolver annotates ast nodes in place, so one instance can't appear in two
+ clauses of the same query.
+ """
+ variant_condition = ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=self.variant_value(),
+ right=ast.Constant(value=variant_keys),
+ )
+ if self.used_fallback:
+ # The default exposure event has only ever been captured server-side, so it can't match
+ # a session. posthog-js stamps `$feature/<flag_key>` on every client event captured
+ # after flags load, so the stamped property stands in — the same fallback the tab's list
+ # uses. It means "the flag was active in this session", not "this is where they were
+ # enrolled", and the variant is the flag's value per event rather than the exposure
+ # response, so a re-bucketed returning person can land in either arm.
+ return variant_condition
+ conditions = [
+ *build_exposure_event_conditions(
+ self.experiment.exposure_criteria,
+ self.team,
+ self.experiment.feature_flag.key,
+ default_exposure_event=self.default_exposure_event,
+ ),
+ variant_condition,
+ ]
+ return ast.And(exprs=conditions) if len(conditions) > 1 else conditions[0]
+
+
+def resolve_session_exposure(team: Team, experiment: Experiment, *, event_names: frozenset[str]) -> SessionExposure:
+ """Resolve how this experiment's exposure reads on sessions.
+
+ `event_names` are the surface's own events — its metrics' — looked up for session linkability in
+ the same bounded `EventProperty` read as the exposure event's, so one query settles both which
+ metrics a session can show and whether the exposure event can match a session at all.
+ """
+ flag_key = experiment.feature_flag.key
+ default_exposure_event = resolve_default_exposure_event(team, experiment.start_date)
+ exposure_event, variant_property = get_exposure_event_and_property(
+ flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event
+ )
+ never_linked = never_session_linked_events(
+ team, event_names | ({exposure_event} if exposure_event is not None else frozenset())
+ )
+ # Both default exposure events mean "this user was enrolled via the flag", which the stamped
+ # flag property implies too, so either can take the fallback.
+ used_fallback = (
+ exposure_event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT) and exposure_event in never_linked
+ )
+ return SessionExposure(
+ team=team,
+ experiment=experiment,
+ default_exposure_event=default_exposure_event,
+ exposure_event=exposure_event,
+ variant_property=f"$feature/{flag_key}" if used_fallback else variant_property,
+ never_linked=never_linked,
+ used_fallback=used_fallback,
+ )
diff --git a/products/experiments/backend/test/test_session_event_deltas_api.py b/products/experiments/backend/test/test_session_event_deltas_api.py
new file mode 100644
index 000000000000..ae85819f3dd5
--- /dev/null
+++ b/products/experiments/backend/test/test_session_event_deltas_api.py
@@ -0,0 +1,594 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from freezegun import freeze_time
+from posthog.test.base import ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import EventProperty, Team, User
+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.actions.backend.models.action import Action
+from products.experiments.backend import session_event_deltas
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.session_event_deltas import EXPERIMENT_BEHAVIOR_COMPARISON_FLAG
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+from ee.api.test.base import APILicensedTest
+
+NOW = datetime(2026, 1, 10, 12, 0, 0, tzinfo=UTC)
+EXPERIMENT_START = datetime(2026, 1, 1, tzinfo=UTC)
+EXPOSED_AT = datetime(2026, 1, 9, 10, 0, 0, tzinfo=UTC)
+
+PURCHASE_METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "11111111-1111-1111-1111-111111111111",
+ "name": "Purchases",
+ "source": {"kind": "EventsNode", "event": "purchase"},
+}
+# No session in `_session` ever fires this event, so it never gets an EventProperty row linking it
+# to `$session_id` — the shape of an event only ever captured from a backend SDK.
+SERVER_SIDE_METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "22222222-2222-2222-2222-222222222222",
+ "name": "Server charges",
+ "source": {"kind": "EventsNode", "event": "server charge"},
+}
+
+
+def rank_anything(test: Any) -> Any:
+ """Drop the evidence floors for tests about which sessions, people and recordings are counted.
+
+ Those fixtures are a handful of people by design, which the floors are built to reject —
+ without this they'd assert on an empty shelf and pass whatever the counting did.
+ """
+ for constant, value in (
+ ("CONFIDENCE_Z", 0.0),
+ ("MIN_LOG_RATIO_LOWER_BOUND", 0.0),
+ ("MIN_SUPPORT_PERSONS", 1),
+ ("MIN_ARM_PERSONS", 1),
+ ):
+ test = patch.object(session_event_deltas, constant, value)(test)
+ return test
+
+
+@freeze_time(NOW)
+class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self._people: set[str] = set()
+ flag_patch = patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=lambda flag, *args, **kwargs: flag == EXPERIMENT_BEHAVIOR_COMPARISON_FLAG,
+ )
+ flag_patch.start()
+ self.addCleanup(flag_patch.stop)
+
+ def _create_experiment(
+ self,
+ metrics: Optional[list[dict[str, Any]]] = None,
+ key: str = "checkout-cta",
+ variants: Optional[list[str]] = None,
+ exposure_criteria: Optional[dict[str, Any]] = None,
+ team: Optional[Team] = None,
+ created_by: Optional[User] = None,
+ ) -> Experiment:
+ team = team or self.team
+ flag = FeatureFlag.objects.create(
+ team=team,
+ key=key,
+ name=key,
+ created_by=self.user,
+ filters={
+ "multivariate": {
+ "variants": [{"key": key, "rollout_percentage": 50} for key in variants or ["control", "test"]]
+ }
+ },
+ )
+ return Experiment.objects.create(
+ team=team,
+ name="Checkout CTA copy",
+ feature_flag=flag,
+ created_by=created_by or self.user,
+ start_date=EXPERIMENT_START,
+ exposure_criteria=exposure_criteria or {},
+ metrics=metrics or [],
+ )
+
+ def _session(
+ self,
+ *,
+ variants: Optional[list[str]] = None,
+ events: Optional[list[str]] = None,
+ at: datetime = EXPOSED_AT,
+ flag_key: str = "checkout-cta",
+ distinct_id: Optional[str] = None,
+ properties: Optional[dict[str, Any]] = None,
+ recorded: bool = True,
+ ) -> str:
+ """One session: an exposure event per entry in `variants`, then `events`.
+
+ A distinct_id of its own unless one is passed, because the comparison counts people —
+ reusing one across sessions is what the returning-person case is about, not the default.
+
+ Recorded by default, since a card can only carry sessions replay kept; `recorded=False`
+ is the sampled-out session that must never back a card.
+ """
+ distinct_id = distinct_id or f"person{len(self._people)}"
+ if distinct_id not in self._people:
+ # Without a person row every event resolves to a random person_id, which would put each
+ # of a person's sessions in its own arm total.
+ _create_person(team=self.team, distinct_ids=[distinct_id])
+ self._people.add(distinct_id)
+
+ session_id = str(uuid7(unix_ms_time=int(at.timestamp() * 1000)))
+ shared_properties = {"$session_id": session_id, **(properties or {})}
+ exposure_variants = variants if variants is not None else ["test"]
+ for index, variant in enumerate(exposure_variants):
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id=distinct_id,
+ timestamp=at + timedelta(seconds=index),
+ properties={
+ **shared_properties,
+ "$feature_flag": flag_key,
+ "$feature_flag_response": variant,
+ },
+ )
+ for index, event in enumerate(events or []):
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=distinct_id,
+ timestamp=at + timedelta(minutes=index + 1),
+ properties=shared_properties,
+ )
+ if recorded:
+ produce_replay_summary(
+ team_id=self.team.pk,
+ session_id=session_id,
+ distinct_id=distinct_id,
+ first_timestamp=at,
+ last_timestamp=at + timedelta(minutes=len(events or []) + 1),
+ # The helper's convenience event would pollute the event counts the cards compare.
+ ensure_analytics_event_in_session=False,
+ )
+ # Ingestion records every (event, property) pair in Postgres, and the endpoint reads those
+ # rows to decide whether an event can back a recording at all — so events captured with a
+ # $session_id here must leave the same trace they would in production, and an exposure event
+ # this session never fired must leave none.
+ for event_name in {*(events or []), *(["$feature_flag_called"] if exposure_variants else [])}:
+ EventProperty.objects.get_or_create(
+ team=self.team, project_id=self.team.project_id, event=event_name, property="$session_id"
+ )
+ return session_id
+
+ def _arm(self, variant: str, sessions: list[list[str]]) -> None:
+ """One person per session — the shape of an arm where nobody comes back."""
+ for events in sessions:
+ self._session(variants=[variant], events=events)
+
+ def _post_deltas(self, experiment: Experiment, **body: Any) -> Any:
+ return self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/session_event_deltas/",
+ body,
+ format="json",
+ )
+
+ def _cards(self, data: dict[str, Any], kind: Optional[str] = None) -> list[dict[str, Any]]:
+ return [card for card in data["cards"] if kind is None or card["kind"] == kind]
+
+ @patch.object(session_event_deltas, "MIN_ARM_PERSONS", 20)
+ def test_cards_rank_by_separation_and_leave_out_what_the_arms_share(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ # The test variant sees pricing_faq far more and reaches checkout far less. `noise` differs
+ # by a couple of people, which is nothing over thirty; `rare` happened once.
+ self._arm("control", [["pricing_faq"], ["pricing_faq"]] + [["checkout_start", "noise"]] * 20 + [[]] * 8)
+ self._arm("test", [["pricing_faq", "noise"]] * 22 + [["checkout_start"]] * 4 + [["rare"]] + [[]] * 3)
+ flush_persons_and_events()
+
+ response = self._post_deltas(experiment)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ data = response.json()
+ behavior = self._cards(data, "behavior")
+ # Ranked on how far apart the arms are, not on which way — an event the test variant does
+ # much *less* has to be able to earn a card on the arm that does it more.
+ assert [(card["event"], card["variant"]) for card in behavior] == [
+ ("pricing_faq", "test"),
+ ("checkout_start", "control"),
+ ]
+ # A band, never a number: the experiment's own results state magnitudes, and a second one
+ # computed from a different window and unit would read as a contradiction.
+ assert behavior[0]["strength"] == "more"
+ assert {"ratio", "baseline_rate", "target_rate"}.isdisjoint(behavior[0])
+ # Every card is backed by actual recordings, most recent first.
+ assert all(card["recording_count"] == len(card["session_ids"]) > 0 for card in behavior)
+ # An event the arms share and one person's one-off get no card at all.
+ assert {"noise", "rare"}.isdisjoint({card["event"] for card in behavior})
+ assert data["too_early"] is False
+ assert [(arm["key"], arm["persons"]) for arm in data["arms"]] == [("control", 30), ("test", 30)]
+
+ @rank_anything
+ def test_cards_carry_only_sessions_that_were_actually_recorded(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ recorded = self._session(variants=["test"], events=["pricing_faq"])
+ self._session(variants=["test"], events=["pricing_faq"], recorded=False)
+ self._session(variants=["control"], events=["checkout_start"], recorded=False)
+ self._session(variants=["control"], events=[])
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ cards = {card["event"]: card for card in self._cards(data)}
+ # Two test people did pricing_faq, but only one session was recorded — the card promises
+ # exactly what the playlist can show.
+ assert cards["pricing_faq"]["session_ids"] == [recorded]
+ assert cards["pricing_faq"]["recording_count"] == 1
+ # checkout_start only ever happened in an unrecorded session: no card, not an empty card.
+ assert "checkout_start" not in cards
+
+ @rank_anything
+ def test_a_person_is_counted_once_and_read_from_their_first_exposed_session(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ self._session(variants=["control"], events=["pricing_faq"], distinct_id="comes_back", at=EXPOSED_AT)
+ for index in range(3):
+ self._session(
+ variants=["control"],
+ events=["checkout_start"],
+ distinct_id="comes_back",
+ at=EXPOSED_AT + timedelta(hours=index + 1),
+ )
+ self._session(variants=["test"], events=["checkout_start"], distinct_id="visits_once")
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # The comparison reads each person from their first covered session only — reading all four
+ # would give this arm four times the chance to have done something. So checkout_start is a
+ # difference on the *test* side, even though control's later sessions are full of it.
+ checkout = next(card for card in self._cards(data, "behavior") if card["event"] == "checkout_start")
+ assert checkout["variant"] == "test"
+ # People counted once; the sessions total still says how much material sits behind the arm.
+ assert [(arm["persons"], arm["sessions"]) for arm in data["arms"]] == [(1, 4), (1, 1)]
+
+ @parameterized.expand(
+ [
+ # (name, multiple_variant_handling, expected people per arm, expected excluded)
+ ("exclude", "exclude", [1, 1], 1),
+ # First-seen puts the person in the arm they saw first, so nobody is set aside.
+ ("first_seen", "first_seen", [1, 2], 0),
+ ]
+ )
+ @rank_anything
+ def test_a_person_who_saw_both_variants_is_split_the_way_the_analysis_splits_them(
+ self, _name: str, handling: str, expected_arms: list[int], expected_multiple: int
+ ) -> None:
+ experiment = self._create_experiment(
+ metrics=[PURCHASE_METRIC], exposure_criteria={"multiple_variant_handling": handling}
+ )
+ self._session(variants=["control"], events=["pricing_faq"])
+ self._session(variants=["test"], events=["pricing_faq"])
+ self._session(variants=["test", "control"], events=["pricing_faq"])
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ assert [arm["persons"] for arm in data["arms"]] == expected_arms
+ assert data["multiple_variant_persons"] == expected_multiple
+ assert data["multiple_variant_handling"] == handling
+
+ @rank_anything
+ def test_one_vs_rest_puts_the_card_on_the_arm_that_stands_out(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], variants=["control", "test", "other"])
+ self._arm("control", [["dashboard_viewed"]] * 2)
+ self._arm("test", [["dashboard_viewed"]] * 2)
+ self._arm("other", [["dashboard_viewed", "tree_opened"]] * 2)
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ cards = self._cards(data, "behavior")
+ # tree_opened is distinctive to `other` against the rest pooled; dashboard_viewed is
+ # everywhere, so it is nobody's finding.
+ assert [(card["event"], card["variant"]) for card in cards] == [("tree_opened", "other")]
+
+ @rank_anything
+ def test_metric_events_get_shortcut_cards_and_never_comparisons(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC, SERVER_SIDE_METRIC])
+ self._arm("control", [["purchase", "pricing_faq"]] * 2)
+ self._arm("test", [["pricing_faq"], []])
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # `purchase` is this experiment's primary metric: the results tab states what happened to
+ # it, so here it only links to recordings of it happening, with no band and no claim.
+ assert all(card["event"] != "purchase" for card in self._cards(data, "behavior"))
+ metric_cards = self._cards(data, "metric")
+ assert [(card["event"], card["variant"], card["strength"]) for card in metric_cards] == [
+ ("purchase", "control", None)
+ ]
+ assert metric_cards[0]["metric_name"] == "Purchases"
+ # The server-side metric can never back a recording, so it gets no card rather than an
+ # empty one; it is still named for the caption.
+ assert data["metric_events"] == ["purchase", "server charge"]
+
+ @rank_anything
+ def test_metric_cards_respect_the_metrics_property_filters(self) -> None:
+ experiment = self._create_experiment(
+ metrics=[
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "33333333-3333-3333-3333-333333333333",
+ "name": "Enterprise purchases",
+ "source": {
+ "kind": "EventsNode",
+ "event": "purchase",
+ "properties": [{"key": "plan", "value": "enterprise", "operator": "exact", "type": "event"}],
+ },
+ }
+ ]
+ )
+ self._session(variants=["control"], events=[])
+ matching = self._session(variants=["test"], events=["purchase"], properties={"plan": "enterprise"})
+ self._session(variants=["test"], events=["purchase"], properties={"plan": "free"})
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # The card carries the metric's name, so a purchase outside the metric's filter on it would
+ # be a mislabeled recording, not a shortcut to the metric happening.
+ metric_cards = self._cards(data, "metric")
+ assert [(card["event"], card["variant"]) for card in metric_cards] == [("purchase", "test")]
+ assert metric_cards[0]["session_ids"] == [matching]
+ assert metric_cards[0]["recording_count"] == 1
+
+ @rank_anything
+ def test_friction_events_land_on_their_own_shelf(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ self._arm("control", [["pricing_faq"]] * 2)
+ self._arm("test", [["$exception"], ["$exception", "pricing_faq"]])
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ friction = self._cards(data, "friction")
+ assert [(card["event"], card["variant"]) for card in friction] == [("$exception", "test")]
+
+ def test_too_early_is_reported_rather_than_an_empty_shelf(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ self._session(variants=["control"], events=["pricing_faq"])
+ self._session(variants=["test"], events=["checkout_start"])
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # Two people against a floor of fifty: an empty shelf here would read as "the variants
+ # behaved identically", which two people cannot establish.
+ assert data["too_early"] is True
+ assert data["cards"] == []
+ assert data["min_arm_persons"] == session_event_deltas.MIN_ARM_PERSONS
+
+ @rank_anything
+ @patch.object(session_event_deltas, "MAX_DELTA_SCAN_SESSIONS", 1)
+ def test_reports_the_window_it_could_cover_rather_than_the_one_it_was_asked_for(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ self._session(variants=["control"], events=["pricing_faq"], at=EXPERIMENT_START + timedelta(hours=1))
+ self._session(variants=["test"], events=["pricing_faq"], at=EXPOSED_AT)
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # Only the most recent session fits, so the experiment's own start date would claim eight
+ # days of coverage that was never read — and the scan itself would read them for nothing.
+ # What's left is that session's own day, plus the longest a session it began in could run.
+ assert data["sessions_truncated"] is True
+ assert datetime.fromisoformat(data["date_from"]) == EXPOSED_AT - timedelta(
+ hours=session_event_deltas.MAX_SESSION_DURATION_HOURS
+ )
+
+ @rank_anything
+ def test_default_exposure_falls_back_to_the_stamped_flag_property(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ # No exposure event carries a $session_id here, the shape of an experiment whose flag is
+ # only ever evaluated server-side. The property posthog-js stamps on every client event has
+ # to stand in, or the whole shelf compares nothing.
+ recorded = self._session(variants=[], events=["pricing_faq"], properties={"$feature/checkout-cta": "test"})
+ self._session(variants=[], events=["pricing_faq"], properties={"$feature/checkout-cta": "test"})
+ self._session(variants=[], events=["checkout_start"], properties={"$feature/checkout-cta": "control"})
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ assert data["used_exposure_fallback"] is True
+ assert [(arm["key"], arm["persons"]) for arm in data["arms"]] == [("control", 1), ("test", 2)]
+ pricing_faq = next(card for card in self._cards(data, "behavior") if card["event"] == "pricing_faq")
+ assert pricing_faq["variant"] == "test"
+ assert recorded in pricing_faq["session_ids"]
+
+ @rank_anything
+ def test_fallback_comparison_is_clamped_to_its_own_tighter_window(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ # The stamped flag property rides on every client event, so on the fallback path there is
+ # no event name for the scan to prune on and the window is the only thing bounding it. A
+ # session inside the experiment's window but past the fallback clamp must fall out of the
+ # comparison rather than be read.
+ self._session(variants=[], events=["pricing_faq"], properties={"$feature/checkout-cta": "test"})
+ self._session(variants=[], events=["checkout_start"], properties={"$feature/checkout-cta": "control"})
+ self._session(
+ variants=[],
+ events=["old_event"],
+ properties={"$feature/checkout-cta": "control"},
+ at=NOW - timedelta(days=4),
+ )
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ assert data["used_exposure_fallback"] is True
+ assert datetime.fromisoformat(data["date_from"]) == NOW - timedelta(
+ days=session_event_deltas.MAX_FALLBACK_DELTA_SCAN_DAYS
+ )
+ assert [(arm["key"], arm["persons"]) for arm in data["arms"]] == [("control", 1), ("test", 1)]
+ assert all(card["event"] != "old_event" for card in data["cards"])
+
+ @parameterized.expand([("exclude", "exclude"), ("first_seen", "first_seen")])
+ @rank_anything
+ def test_sharing_a_session_with_someone_elses_exposure_does_not_reattribute_a_person(
+ self, _name: str, handling: str
+ ) -> None:
+ experiment = self._create_experiment(
+ metrics=[PURCHASE_METRIC], exposure_criteria={"multiple_variant_handling": handling}
+ )
+ # Server-side events can reuse a client session's $session_id under their own person, so a
+ # covered session can hold a second person who was never exposed in it. That person's
+ # (person, session) group carries no exposure rows at all, and the attribution must not
+ # read it as "saw another variant" (exclude) or as "their earliest exposure" (first seen).
+ shared = self._session(
+ variants=["control"],
+ events=["checkout_start"],
+ distinct_id="owns_shared_session",
+ at=EXPOSED_AT - timedelta(hours=1),
+ )
+ self._session(variants=["test"], events=["pricing_faq"], distinct_id="strays_into_it", at=EXPOSED_AT)
+ _create_event(
+ team=self.team,
+ event="backend_ping",
+ distinct_id="strays_into_it",
+ timestamp=EXPOSED_AT - timedelta(minutes=30),
+ properties={"$session_id": shared},
+ )
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ assert [(arm["key"], arm["persons"]) for arm in data["arms"]] == [("control", 1), ("test", 1)]
+ assert data["multiple_variant_persons"] == 0
+ # The shared session started before their own, so an unconditioned "first covered session"
+ # would read the strayer's behavior as backend_ping and lose pricing_faq — behavior comes
+ # from the first session they were exposed in, and only exposed sessions count.
+ assert sorted((card["event"], card["variant"]) for card in self._cards(data, "behavior")) == [
+ ("checkout_start", "control"),
+ ("pricing_faq", "test"),
+ ]
+ assert [(arm["key"], arm["sessions"]) for arm in data["arms"]] == [("control", 1), ("test", 1)]
+
+ # The fixture produces exactly five (event x arm) rows: two totals, 'faq' in both arms, and
+ # 'rare_event' in one. The cap can't tell "exactly at the ceiling" from "cut short" unless the
+ # query fetches one row past it, so both sides of the boundary are pinned. Past the cap,
+ # 'rare_event' sorts last and must vanish whole — a card built on a partial read would claim
+ # one arm never did it — while the totals sort first, so the arms' counts survive any cut.
+ @parameterized.expand(
+ [
+ ("exactly_at_cap", 5, False, [("rare_event", "test")]),
+ ("past_cap", 4, True, []),
+ ]
+ )
+ @rank_anything
+ def test_event_row_cap_drops_whole_events_only_past_the_cap(
+ self, _name: str, cap: int, truncated: bool, expected_cards: list[tuple[str, str]]
+ ) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ self._session(variants=["control"], events=["faq"])
+ self._session(variants=["test"], events=["faq", "rare_event"])
+ flush_persons_and_events()
+
+ with patch.object(session_event_deltas, "MAX_DELTA_EVENT_ROWS", cap):
+ data = self._post_deltas(experiment).json()
+
+ assert data["events_truncated"] is truncated
+ assert [(card["event"], card["variant"]) for card in self._cards(data, "behavior")] == expected_cards
+ assert [(arm["key"], arm["persons"]) for arm in data["arms"]] == [("control", 1), ("test", 1)]
+
+ @rank_anything
+ def test_an_action_based_exposure_still_backs_its_cards_with_recordings(self) -> None:
+ action = Action.objects.create(
+ team=self.team, name="Reached checkout", steps_json=[{"event": "checkout_viewed"}]
+ )
+ experiment = self._create_experiment(
+ metrics=[PURCHASE_METRIC], exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.id}}
+ )
+ exposed = {"$feature/checkout-cta": "test"}
+ recorded = self._session(variants=[], events=["checkout_viewed", "pricing_faq"], properties=exposed)
+ self._session(variants=[], events=["checkout_viewed", "pricing_faq"], properties=exposed)
+ self._session(variants=[], events=["checkout_viewed"], properties={"$feature/checkout-cta": "control"})
+ flush_persons_and_events()
+
+ data = self._post_deltas(experiment).json()
+
+ # An action can match several events, so it resolves to no single event name. The query
+ # that backs a card with recordings still has to reach the exposure rows carrying the
+ # variant: without them every session reads as variant-less, every card is dropped as
+ # unbacked, and the shelf says "no variant behaves differently" on an experiment it never
+ # managed to compare.
+ pricing_faq = next(card for card in self._cards(data, "behavior") if card["event"] == "pricing_faq")
+ assert pricing_faq["variant"] == "test"
+ assert recorded in pricing_faq["session_ids"]
+
+ def test_server_side_exposure_event_is_refused_rather_than_silently_empty(self) -> None:
+ experiment = self._create_experiment(
+ metrics=[PURCHASE_METRIC],
+ exposure_criteria={
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "server exposure",
+ "properties": [],
+ }
+ },
+ )
+ self._session(variants=[], events=["purchase"], properties={"$feature/checkout-cta": "test"})
+ flush_persons_and_events()
+
+ response = self._post_deltas(experiment)
+
+ # An exposure event no session can carry compares nothing, and an empty shelf reads as
+ # "the variants behaved identically" rather than "this can't be answered from recordings".
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "captured server-side" in response.json()["detail"]
+
+ @rank_anything
+ def test_recordings_the_viewer_cannot_open_are_left_off_the_cards(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+ denied = self._session(variants=["test"], events=["pricing_faq"])
+ allowed = self._session(variants=["test"], events=["pricing_faq"])
+ self._session(variants=["control"], events=[])
+ # Object-level controls can only target a recording that has a Postgres row.
+ SessionRecording.objects.create(team=self.team, session_id=denied)
+ flush_persons_and_events()
+
+ # Only that one recording is denied: the same check guards the experiment itself, and
+ # failing it there would 500 the request rather than test anything.
+ with patch(
+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",
+ side_effect=lambda obj, *args, **kwargs: getattr(obj, "session_id", None) != denied,
+ ):
+ data = self._post_deltas(experiment).json()
+
+ # A card hands its ids straight to the playlist, so leaving a denied recording on one would
+ # tell the viewer its id, the variant it was in, and an event it contains.
+ card = next(card for card in self._cards(data, "behavior") if card["event"] == "pricing_faq")
+ assert card["session_ids"] == [allowed]
+ assert card["recording_count"] == 1
+
+ def test_requires_session_replay_access(self) -> None:
+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])
+
+ with patch(
+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_resource", return_value=False
+ ):
+ response = self._post_deltas(experiment)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 4b2ea4a55af1..078f4dad6c32 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2253,6 +2253,136 @@ export interface ExperimentSessionBucketResponseApi {
used_exposure_fallback: boolean
}
+/**
+ * * `behavior` - behavior
+ * * `friction` - friction
+ * * `metric` - metric
+ */
+export type ExperimentWatchCardKindEnumApi =
+ (typeof ExperimentWatchCardKindEnumApi)[keyof typeof ExperimentWatchCardKindEnumApi]
+
+export const ExperimentWatchCardKindEnumApi = {
+ Behavior: 'behavior',
+ Friction: 'friction',
+ Metric: 'metric',
+} as const
+
+/**
+ * * `only` - only
+ * * `far_more` - far_more
+ * * `more` - more
+ * * `slightly_more` - slightly_more
+ */
+export type ExperimentWatchCardStrengthEnumApi =
+ (typeof ExperimentWatchCardStrengthEnumApi)[keyof typeof ExperimentWatchCardStrengthEnumApi]
+
+export const ExperimentWatchCardStrengthEnumApi = {
+ Only: 'only',
+ FarMore: 'far_more',
+ More: 'more',
+ SlightlyMore: 'slightly_more',
+} as const
+
+/**
+ * One group of recordings worth opening, and the sentence that justifies it.
+ *
+ * Deliberately no rate, no ratio and no person count: a precise number next to an event name is
+ * an effect size, and the experiment's results publish those for everything it measures, computed
+ * over a different window and a different unit. The only number here is how many recordings the
+ * card can actually show.
+ */
+export interface ExperimentWatchCardApi {
+ /** What the card is: 'behavior' for an event this variant did clearly more than the other variants together, 'friction' for the same finding on an error or rage signal, 'metric' for a shortcut to recordings around one of the experiment's own metric events. Metric cards claim nothing about how the metric moved: that is the experiment results' answer.
+ *
+ * * `behavior` - behavior
+ * * `friction` - friction
+ * * `metric` - metric */
+ kind: ExperimentWatchCardKindEnumApi
+ /** The event behind the card. */
+ event: string
+ /** The variant whose recordings these are: for comparison cards, the one that did the event more. */
+ variant: string
+ /** How far apart this variant and the rest are, as a band rather than a number: 'only' when nobody in the other variants did it at all among the people compared, then 'far_more', 'more' and 'slightly_more'. Read off the conservative end of the difference, so a card that clears the bar only because the sample is large reports as slight. Null on metric cards, which compare nothing. Present a band as a comparison ('far more common in test'), never convert it into a multiple.
+ *
+ * * `only` - only
+ * * `far_more` - far_more
+ * * `more` - more
+ * * `slightly_more` - slightly_more */
+ strength: ExperimentWatchCardStrengthEnumApi | null
+ /**
+ * The metric whose event this card shortcuts to. Null outside metric cards.
+ * @nullable
+ */
+ metric_name: string | null
+ /** How many recordings the card carries, at most 20. Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. */
+ recording_count: number
+ /** The recordings themselves, most recent first, ready to hand to the recordings list as-is. */
+ session_ids: string[]
+}
+
+/**
+ * One variant's compared population.
+ */
+export interface ExperimentWatchArmApi {
+ /** The variant key. */
+ key: string
+ /** Exposed people the comparison covered for this variant. People rather than sessions because a variant can change how often the flag is evaluated again later, which moves a variant's session count without anyone behaving differently. Each person is read from the first session the comparison covers them in, so every variant gets the same amount of behavior per person. */
+ persons: number
+ /** Exposed sessions those people were seen in, which is more than the comparison reads: it says how much recorded material sits behind the variant. */
+ sessions: number
+}
+
+/**
+ * * `exclude` - exclude
+ * * `first_seen` - first_seen
+ */
+export type ExperimentWatchMultipleVariantHandlingEnumApi =
+ (typeof ExperimentWatchMultipleVariantHandlingEnumApi)[keyof typeof ExperimentWatchMultipleVariantHandlingEnumApi]
+
+export const ExperimentWatchMultipleVariantHandlingEnumApi = {
+ Exclude: 'exclude',
+ FirstSeen: 'first_seen',
+} as const
+
+/**
+ * The recordings worth watching for this experiment, grouped into cards.
+ *
+ * Descriptive, never a result: cards say where behavior visibly differed and hand over the
+ * recordings, while the experiment's results measure its metrics over the whole run window and
+ * state the magnitudes. Nothing here says a variant is winning.
+ */
+export interface ExperimentSessionEventDeltaResponseApi {
+ /** The shelf, strongest comparison first, then metric shortcuts. Events the variants can't be told apart on get no card at all rather than a weak one, so an empty shelf means no difference was big enough to be sure of, not that nothing was measured. The experiment's own metric events never appear as comparisons: see metric_events. */
+ cards: ExperimentWatchCardApi[]
+ /** Every variant's compared population, in the flag's variant order. */
+ arms: ExperimentWatchArmApi[]
+ /** People who saw more than one variant and were left out of every card. Always 0 when the experiment attributes such users to the variant they saw first. */
+ multiple_variant_persons: number
+ /** How the experiment handles someone who saw more than one variant, followed here so the cards split their people the same way the analysis does.
+ *
+ * * `exclude` - exclude
+ * * `first_seen` - first_seen */
+ multiple_variant_handling: ExperimentWatchMultipleVariantHandlingEnumApi
+ /** The experiment's own metric events, which never enter the behavior comparison. They are the events it was built to move, so they would top the ranking on nearly every experiment, and the experiment's results already say what happened to them with the statistics that go with a result. They can appear as 'metric' shortcut cards, which claim nothing. */
+ metric_events: string[]
+ /** Start of what was actually compared. The requested window is the experiment's run window clamped to its most recent 14 days (2 when sessions are matched on the stamped flag property, which no event name can prune a scan on), but a busy experiment reaches the session ceiling long before that, and this reports where the compared sessions really begin - often hours rather than days back. Display this, not the experiment's own dates. */
+ date_from: string
+ /** End of what was compared: the experiment's end date, or now while it runs. */
+ 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
+ /** True when the compared sessions were matched on the stamped $feature/<flag key> event property instead of the exposure event, because the default exposure event has only ever been captured server-side and can never match a session. The sessions then mean 'the flag was active in this session', and the variant comes from the flag's value on each event, so a returning user can be counted under a variant they were re-bucketed into later. */
+ used_exposure_fallback: boolean
+ /** True when the experiment had more exposed sessions in the requested window than one comparison covers, so the most recent ones were used and date_from is later than the experiment's own window. Every variant is still covered over the same stretch of time. */
+ sessions_truncated: boolean
+ /** True when the project has more distinct event names in the window than one comparison can rank, so some were never considered. */
+ events_truncated: boolean
+ /** How many exposed people a variant needs before it can be compared at all. Below it a variant's cards would be noise whatever the evidence bar allows. */
+ min_arm_persons: number
+ /** True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and cards is empty. Say 'too early to compare' and show the arms' counts; an empty shelf presented without this would read as 'the variants behaved identically'. */
+ too_early: boolean
+}
+
export interface ShipVariantApi {
/** The conclusion of the experiment.
*
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index a5c6e2aa730f..dd54753ccd4f 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -27,6 +27,7 @@ import type {
ExperimentSessionContextResponseApi,
ExperimentSessionContextsRequestApi,
ExperimentSessionContextsResponseApi,
+ ExperimentSessionEventDeltaResponseApi,
ExperimentWriteApi,
ExperimentsActivityRetrieveParams,
ExperimentsListParams,
@@ -898,6 +899,40 @@ export const experimentsSessionBucketsCreate = async (
})
}
+export const getExperimentsSessionEventDeltasCreateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/experiments/${id}/session_event_deltas/`
+}
+
+/**
+ * The recordings worth watching for this experiment, grouped into cards.
+ *
+ * Each card is one sentence and the recordings that back it: an event one variant did clearly
+ * more than the others, an error signal concentrated in one variant, or a shortcut to a
+ * metric event happening on screen. Every card's count is a count of recordings that actually
+ * exist, so handing its session ids to the recordings list can't come back empty. POST to
+ * take the same throttle and cache posture as the other reads in this family rather than
+ * because it carries a body: it takes no parameters, and it only reads.
+ *
+ * It reports no effect size. The experiment's own metric events never enter the comparison,
+ * and cards carry a direction and a band rather than a rate, a ratio or a person count: the
+ * experiment's results already state magnitudes, computed per person over the whole run
+ * window, and this reads one session per person over a clamped one. Two numbers for the same
+ * event would read as a contradiction, so this surface states none.
+ */
+export const experimentsSessionEventDeltasCreate = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<ExperimentSessionEventDeltaResponseApi> => {
+ return apiMutator<ExperimentSessionEventDeltaResponseApi>(
+ getExperimentsSessionEventDeltasCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
export const getExperimentsShipVariantCreateUrl = (projectId: string, id: number) => {
return `/api/projects/${projectId}/experiments/${id}/ship_variant/`
}
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index 898678ac87ac..65a2289c80ce 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -1356,6 +1356,9 @@ tools:
experiments-session-contexts-create:
operation: experiments_session_contexts_create
enabled: false
+ experiments-session-event-deltas-create:
+ operation: experiments_session_event_deltas_create
+ enabled: false
experiments-update:
operation: experiments_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3cf527c1ad99..d7c29237b51c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30273,6 +30273,136 @@ export namespace Schemas {
results: ExperimentSessionContextResponse[];
}
+ /**
+ * * `behavior` - behavior
+ * * `friction` - friction
+ * * `metric` - metric
+ */
+ export type ExperimentWatchCardKindEnum = typeof ExperimentWatchCardKindEnum[keyof typeof ExperimentWatchCardKindEnum];
+
+
+ export const ExperimentWatchCardKindEnum = {
+ Behavior: 'behavior',
+ Friction: 'friction',
+ Metric: 'metric',
+ } as const;
+
+ /**
+ * * `only` - only
+ * * `far_more` - far_more
+ * * `more` - more
+ * * `slightly_more` - slightly_more
+ */
+ export type ExperimentWatchCardStrengthEnum = typeof ExperimentWatchCardStrengthEnum[keyof typeof ExperimentWatchCardStrengthEnum];
+
+
+ export const ExperimentWatchCardStrengthEnum = {
+ Only: 'only',
+ FarMore: 'far_more',
+ More: 'more',
+ SlightlyMore: 'slightly_more',
+ } as const;
+
+ /**
+ * One group of recordings worth opening, and the sentence that justifies it.
+ *
+ * Deliberately no rate, no ratio and no person count: a precise number next to an event name is
+ * an effect size, and the experiment's results publish those for everything it measures, computed
+ * over a different window and a different unit. The only number here is how many recordings the
+ * card can actually show.
+ */
+ export interface ExperimentWatchCard {
+ /** What the card is: 'behavior' for an event this variant did clearly more than the other variants together, 'friction' for the same finding on an error or rage signal, 'metric' for a shortcut to recordings around one of the experiment's own metric events. Metric cards claim nothing about how the metric moved: that is the experiment results' answer.
+ *
+ * * `behavior` - behavior
+ * * `friction` - friction
+ * * `metric` - metric */
+ kind: ExperimentWatchCardKindEnum;
+ /** The event behind the card. */
+ event: string;
+ /** The variant whose recordings these are: for comparison cards, the one that did the event more. */
+ variant: string;
+ /** How far apart this variant and the rest are, as a band rather than a number: 'only' when nobody in the other variants did it at all among the people compared, then 'far_more', 'more' and 'slightly_more'. Read off the conservative end of the difference, so a card that clears the bar only because the sample is large reports as slight. Null on metric cards, which compare nothing. Present a band as a comparison ('far more common in test'), never convert it into a multiple.
+ *
+ * * `only` - only
+ * * `far_more` - far_more
+ * * `more` - more
+ * * `slightly_more` - slightly_more */
+ strength: ExperimentWatchCardStrengthEnum | null;
+ /**
+ * The metric whose event this card shortcuts to. Null outside metric cards.
+ * @nullable
+ */
+ metric_name: string | null;
+ /** How many recordings the card carries, at most 20. Every card is backed by recordings that actually exist: a finding whose sessions were never recorded is dropped rather than promised. */
+ recording_count: number;
+ /** The recordings themselves, most recent first, ready to hand to the recordings list as-is. */
+ session_ids: string[];
+ }
+
+ /**
+ * One variant's compared population.
+ */
+ export interface ExperimentWatchArm {
+ /** The variant key. */
+ key: string;
+ /** Exposed people the comparison covered for this variant. People rather than sessions because a variant can change how often the flag is evaluated again later, which moves a variant's session count without anyone behaving differently. Each person is read from the first session the comparison covers them in, so every variant gets the same amount of behavior per person. */
+ persons: number;
+ /** Exposed sessions those people were seen in, which is more than the comparison reads: it says how much recorded material sits behind the variant. */
+ sessions: number;
+ }
+
+ /**
+ * * `exclude` - exclude
+ * * `first_seen` - first_seen
+ */
+ export type ExperimentWatchMultipleVariantHandlingEnum = typeof ExperimentWatchMultipleVariantHandlingEnum[keyof typeof ExperimentWatchMultipleVariantHandlingEnum];
+
+
+ export const ExperimentWatchMultipleVariantHandlingEnum = {
+ Exclude: 'exclude',
+ FirstSeen: 'first_seen',
+ } as const;
+
+ /**
+ * The recordings worth watching for this experiment, grouped into cards.
+ *
+ * Descriptive, never a result: cards say where behavior visibly differed and hand over the
+ * recordings, while the experiment's results measure its metrics over the whole run window and
+ * state the magnitudes. Nothing here says a variant is winning.
+ */
+ export interface ExperimentSessionEventDeltaResponse {
+ /** The shelf, strongest comparison first, then metric shortcuts. Events the variants can't be told apart on get no card at all rather than a weak one, so an empty shelf means no difference was big enough to be sure of, not that nothing was measured. The experiment's own metric events never appear as comparisons: see metric_events. */
+ cards: ExperimentWatchCard[];
+ /** Every variant's compared population, in the flag's variant order. */
+ arms: ExperimentWatchArm[];
+ /** People who saw more than one variant and were left out of every card. Always 0 when the experiment attributes such users to the variant they saw first. */
+ multiple_variant_persons: number;
+ /** How the experiment handles someone who saw more than one variant, followed here so the cards split their people the same way the analysis does.
+ *
+ * * `exclude` - exclude
+ * * `first_seen` - first_seen */
+ multiple_variant_handling: ExperimentWatchMultipleVariantHandlingEnum;
+ /** The experiment's own metric events, which never enter the behavior comparison. They are the events it was built to move, so they would top the ranking on nearly every experiment, and the experiment's results already say what happened to them with the statistics that go with a result. They can appear as 'metric' shortcut cards, which claim nothing. */
+ metric_events: string[];
+ /** Start of what was actually compared. The requested window is the experiment's run window clamped to its most recent 14 days (2 when sessions are matched on the stamped flag property, which no event name can prune a scan on), but a busy experiment reaches the session ceiling long before that, and this reports where the compared sessions really begin - often hours rather than days back. Display this, not the experiment's own dates. */
+ date_from: string;
+ /** End of what was compared: the experiment's end date, or now while it runs. */
+ 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;
+ /** True when the compared sessions were matched on the stamped $feature/<flag key> event property instead of the exposure event, because the default exposure event has only ever been captured server-side and can never match a session. The sessions then mean 'the flag was active in this session', and the variant comes from the flag's value on each event, so a returning user can be counted under a variant they were re-bucketed into later. */
+ used_exposure_fallback: boolean;
+ /** True when the experiment had more exposed sessions in the requested window than one comparison covers, so the most recent ones were used and date_from is later than the experiment's own window. Every variant is still covered over the same stretch of time. */
+ sessions_truncated: boolean;
+ /** True when the project has more distinct event names in the window than one comparison can rank, so some were never considered. */
+ events_truncated: boolean;
+ /** How many exposed people a variant needs before it can be compared at all. Below it a variant's cards would be noise whatever the evidence bar allows. */
+ min_arm_persons: number;
+ /** True when fewer than two variants have min_arm_persons exposed people, so no comparison exists and cards is empty. Say 'too early to compare' and show the arms' counts; an empty shelf presented without this would read as 'the variants behaved identically'. */
+ too_early: boolean;
+ }
+
/**
* The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable