:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): experiment variant targeting in the scanner triggers step (#77966)
Kim Svatos Dugan33c0d8750ce2
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsxindex 6815e0fcfecf..9458d64058a1 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx@@ -2,7 +2,7 @@ import './ScannerTriggers.scss'import { useActions, useValues } from 'kea'-import { LemonBanner, LemonCard, LemonInput, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'+import { LemonBanner, LemonCard, LemonInput, LemonInputSelect, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'import { resolveCategoryDropdownVariant, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'@@ -11,11 +11,14 @@ import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalimport { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'import { FEATURE_FLAGS } from 'lib/constants'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonLabel } from 'lib/lemon-ui/LemonLabel'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'+import { Link } from 'lib/lemon-ui/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { getExperimentVariants } from 'scenes/experiments/utils'import { DurationFilter } from 'scenes/session-recordings/filters/DurationFilter'import {convertUniversalFiltersToRecordingsQuery,@@ -24,6 +27,7 @@ import {} from 'scenes/session-recordings/filters/recordingsQueryConversions'import { RecordingsUniversalFilterAddFilterPopover } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'import { defaultRecordingDurationFilter } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { urls } from 'scenes/urls'import { groupsModel } from '~/models/groupsModel'import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'@@ -95,6 +99,57 @@ function ScannerFilterGroup(): JSX.Element {)}+// Variant selection for a scanner created from an experiment. Compiles the choice into the+// exposure filter in the card below, so users never have to build that filter by hand.+function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { experimentContext } = useValues(replayScannerLogic({ id: scannerId }))+ const { setExperimentVariantKeys, detachExperimentContext } = useActions(replayScannerLogic({ id: scannerId }))++ if (!experimentContext) {+ return null+ }+ const { experiment, variantKeys } = experimentContext+ const variantOptions = getExperimentVariants(experiment).map((variant) => ({+ key: variant.key,+ label: variant.key,+ }))++ return (+ <LemonCard hoverEffect={false} className="p-3 space-y-3" data-attr="vision-experiment-targeting">+ <div className="flex items-start justify-between gap-2">+ <div className="space-y-1">+ <LemonLabel>Experiment targeting</LemonLabel>+ <div className="text-xs text-muted">+ This scanner watches sessions exposed to{' '}+ <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>. Changing variants updates+ the exposure filter below. Filters you add yourself are kept.+ </div>+ </div>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => detachExperimentContext()}+ tooltip="Remove the experiment link and edit the recording filters directly."+ data-attr="vision-experiment-targeting-detach"+ >+ Edit as filters+ </LemonButton>+ </div>+ <div className="max-w-160">+ <LemonInputSelect+ mode="multiple"+ value={variantKeys}+ onChange={(keys) => setExperimentVariantKeys(keys)}+ options={variantOptions}+ placeholder="All variants"+ data-attr="vision-experiment-targeting-variants"+ />+ <div className="text-xs text-muted mt-1">Leave empty to watch every variant.</div>+ </div>+ </LemonCard>+ )+}+export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Element {const { scanner, scannerEstimate, scannerEstimateLoading } = useValues(replayScannerLogic({ id: scannerId }))const { featureFlags } = useValues(featureFlagLogic)@@ -115,6 +170,7 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Elemereturn (<div className="space-y-6">+ <ExperimentTargeting scannerId={scannerId} /><LemonField name="query">{({ value, onChange }) => {const query = value as RecordingsQuery | nulldiff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.tsindex c9650626a593..f83b02fd848c 100644--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts@@ -1,4 +1,5 @@-import { Experiment, PropertyFilterType, PropertyOperator } from '~/types'+import { RecordingsQuery } from '~/queries/schema/schema-general'+import { Experiment, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'import {buildExperimentScannerQuery,@@ -6,6 +7,7 @@ import {experimentScannerParams,parseExperimentScannerParams,reconcileVariantKeys,+ replaceExperimentExposureFilter,} from './experimentTargeting'const experiment = {@@ -127,6 +129,68 @@ describe('experimentTargeting', () => {)})+ it('variant changes swap the exposure filter and keep user-added filters', () => {+ const initial = buildExperimentScannerQuery(experiment, ['test'], false)+ const userFilter = {+ key: '$browser',+ type: PropertyFilterType.Event,+ value: ['Chrome'],+ operator: PropertyOperator.Exact,+ }+ const edited = { ...initial, properties: [userFilter] } as RecordingsQuery++ const updated = replaceExperimentExposureFilter(edited, {+ experiment,+ variantKeys: ['control'],+ useExposureFallback: false,+ })++ expect(updated.events?.[0]?.properties?.[0]).toMatchObject({+ key: '$feature_flag_response',+ value: ['control'],+ })+ expect(updated.properties).toEqual([userFilter])+ })++ it('fallback-mode variant changes keep user event filters and swap only the flag property', () => {+ const initial = buildExperimentScannerQuery(experiment, ['test'], true)+ const userEvent = { id: '$pageview', name: '$pageview', type: 'events' }+ const edited = { ...initial, events: [userEvent] } as RecordingsQuery++ const updated = replaceExperimentExposureFilter(edited, {+ experiment,+ variantKeys: ['control'],+ useExposureFallback: true,+ })++ expect(updated.events).toEqual([expect.objectContaining({ id: '$pageview' })])+ expect(updated.properties).toEqual([+ expect.objectContaining({ key: '$feature/checkout-redesign', value: ['control'] }),+ ])+ })++ it('forces AND when swapping the exposure filter into an OR query', () => {+ const orQuery = {+ ...buildExperimentScannerQuery(experiment, ['test'], false),+ operand: FilterLogicalOperator.Or,+ } as RecordingsQuery+ const updated = replaceExperimentExposureFilter(orQuery, {+ experiment,+ variantKeys: ['test'],+ useExposureFallback: false,+ })+ expect(updated.operand).toEqual(FilterLogicalOperator.And)+ })++ it('inserts the exposure filter when the user removed it', () => {+ const emptied = replaceExperimentExposureFilter(+ { ...buildExperimentScannerQuery(experiment, [], false), events: [] },+ { experiment, variantKeys: ['test'], useExposureFallback: false }+ )+ expect(emptied.events).toHaveLength(1)+ expect(emptied.events?.[0]?.properties?.[0]).toMatchObject({ value: ['test'] })+ })+it.each([['Frustration score', 'Checkout redesign', 'Frustration score: Checkout redesign'],['', 'Checkout redesign', 'Checkout redesign'],diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.tsindex bdf233184146..36539c98a8a8 100644--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts@@ -1,13 +1,23 @@+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'import {getExperimentVariants,getExposureFallbackFilter,getViewRecordingFiltersForVariant,} from 'scenes/experiments/utils'-import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'+import {+ convertUniversalFiltersToRecordingsQuery,+ recordingsQueryToUniversalFilters,+} from 'scenes/session-recordings/filters/recordingsQueryConversions'import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'import { RecordingsQuery } from '~/queries/schema/schema-general'-import { Experiment, FilterLogicalOperator, UniversalFiltersGroupValue } from '~/types'+import {+ Experiment,+ FilterLogicalOperator,+ RecordingUniversalFilters,+ UniversalFiltersGroup,+ UniversalFiltersGroupValue,+} from '~/types'import type { ReplayScanner } from './types'@@ -103,7 +113,7 @@ export function buildExperimentScannerQuery(useExposureFallback: boolean): RecordingsQuery {const exposureFilter = buildExperimentExposureFilter(experiment, variantKeys, useExposureFallback)- const converted = convertUniversalFiltersToRecordingsQuery({+ return toScannerQuery({...DEFAULT_RECORDING_FILTERS,filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,filter_group: {@@ -116,8 +126,84 @@ export function buildExperimentScannerQuery(],},})- // Only the dimensions the Triggers editor persists; the rest (dates, order, session ids) are- // playlist concerns the scanner model strips or never stores.+}++/**+ * True for a filter the experiment targeting compiled: it references the experiment's flag key,+ * either as the `$feature/<flag_key>` variant property (fallback filter, or a property on a+ * custom exposure event) or as a `$feature_flag` property on the default exposure event. User+ * filters on the same flag are indistinguishable by design; the variant selector owns flag+ * targeting while the experiment link is attached.+ */+function isManagedExposureFilter(value: UniversalFiltersGroupValue, experiment: Experiment): boolean {+ if (isUniversalGroupFilterLike(value)) {+ return false+ }+ const variantProperty = `$feature/${experiment.feature_flag_key}`+ if ('key' in value && value.key === variantProperty) {+ return true+ }+ if ('type' in value && (value.type === 'events' || value.type === 'actions')) {+ const properties = ('properties' in value ? value.properties : undefined) ?? []+ return properties.some((property) => {+ if (!property || typeof property !== 'object' || !('key' in property)) {+ return false+ }+ if (property.key === variantProperty) {+ return true+ }+ if (property.key !== '$feature_flag' || !('value' in property)) {+ return false+ }+ return Array.isArray(property.value)+ ? property.value.includes(experiment.feature_flag_key)+ : property.value === experiment.feature_flag_key+ })+ }+ return false+}++/**+ * Swaps the managed exposure filter in an existing scanner query for one targeting `variantKeys`,+ * keeping every other filter the user added. The managed filter is recognized by the experiment's+ * flag key (see `isManagedExposureFilter`); if the user removed it, the new one is inserted at+ * the front.+ */+export function replaceExperimentExposureFilter(+ query: RecordingsQuery | null,+ context: ExperimentScannerContext+): RecordingsQuery {+ const exposureFilter = buildExperimentExposureFilter(+ context.experiment,+ context.variantKeys,+ context.useExposureFallback+ )+ const universal = recordingsQueryToUniversalFilters(query)+ // Forced to AND: a recordings query has a single operand across its whole flattened filter+ // tree, so an OR group would make the exposure filter optional and match unexposed sessions.+ const swapIn = (group: UniversalFiltersGroup): UniversalFiltersGroup => ({+ ...group,+ type: FilterLogicalOperator.And,+ values: [+ ...(exposureFilter ? [exposureFilter] : []),+ ...group.values.filter((value) => !isManagedExposureFilter(value, context.experiment)),+ ],+ })+ const [first, ...rest] = universal.filter_group.values+ const filterGroup: UniversalFiltersGroup =+ first !== undefined && isUniversalGroupFilterLike(first)+ ? { ...universal.filter_group, type: FilterLogicalOperator.And, values: [swapIn(first), ...rest] }+ : swapIn(universal.filter_group)+ return toScannerQuery({ ...universal, filter_group: filterGroup })+}++/**+ * Converts editor-shaped universal filters to the scanner's persisted query, keeping only the+ * dimensions the Triggers editor writes; the rest (dates, order, session ids) are playlist+ * concerns the scanner model strips or never stores.+ */+function toScannerQuery(universal: RecordingUniversalFilters): RecordingsQuery {+ const converted = convertUniversalFiltersToRecordingsQuery(universal)return {kind: converted.kind,events: converted.events,diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex cd13fe1ccf35..9bd2e52270cd 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -66,6 +66,7 @@ import {parseExperimentScannerParams,prefillScannerForExperiment,reconcileVariantKeys,+ replaceExperimentExposureFilter,} from './experimentTargeting'import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'import {@@ -361,6 +362,9 @@ export interface replayScannerLogicActions {copyAllObservationsFinished: () => {value: true}+ detachExperimentContext: () => {+ value: true+ }discardScannerDraft: () => {value: true}@@ -505,6 +509,9 @@ export interface replayScannerLogicActions {setExperimentContext: (context: ExperimentScannerContext | null) => {context: ExperimentScannerContext | null}+ setExperimentVariantKeys: (variantKeys: string[]) => {+ variantKeys: string[]+ }setObservationBackfillFilter: (value: string | null) => {value: string | null}@@ -669,6 +676,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([loadScannerSuccess: (scanner: ScannerFormValues) => ({ scanner }),loadScannerFailure: true,setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),+ setExperimentVariantKeys: (variantKeys: string[]) => ({ variantKeys }),+ detachExperimentContext: true,saveAffectedCohort: (tag?: string) => ({ tag }),setScannerType: (scannerType: ScannerType) => ({ scannerType }),startFromTemplate: (templateKey: string | null) => ({ templateKey }),@@ -911,6 +920,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([null as ExperimentScannerContext | null,{setExperimentContext: (_, { context }) => context,+ setExperimentVariantKeys: (state, { variantKeys }) => (state ? { ...state, variantKeys } : state),+ detachExperimentContext: () => null,},],originalScanner: [@@ -1471,6 +1482,19 @@ export const replayScannerLogic = kea<replayScannerLogicType>([}},+ // The reducer has already stored the new keys; recompile only the managed exposure+ // filter so filters the user added by hand survive a variant change.+ setExperimentVariantKeys: () => {+ const context = values.experimentContext+ if (!context) {+ return+ }+ actions.setScannerValue(+ 'query',+ replaceExperimentExposureFilter(values.scanner?.query ?? null, context)+ )+ },+// Changing type keeps the rest of the form: it spreads `current`, so an experiment// prefill's name and query carry over untouched. Only the config is reset for the new type.setScannerType: ({ scannerType }) => {