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(replay): scope event filters to the recording window behind a flag (#103074)

Paul D'Ambraf080d9098a46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bd11d3356bae..52b1703e75b6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7666,6 +7666,14 @@ snapshots:
hash: v1.k794b7964.bf1fc2024924b2d2d156739c04e8acade818852ad91dfd6e01210665b246149f.6nwqTT8W_PljoKoR11Dup9D06jQVw8-SBZQbAM43gks
replay-tabs-home-failure--not-found--light:
hash: v1.k794b7964.d9b15fdde17563eeb620d2a170d2b73434cc960fb55818fd07bb725d5a077700.LAZBeOy08kO2WM7ec--oJjkn8R_3VYZ-Wqvcg6IDD-8
+ replay-tabs-home-filters-banner--event-match-scope-only-during-recording--dark:
+ hash: v1.k794b7964.e2f4941d60b081b3660e8dba7947eebc5676151aed686f3fa5ca380683fe3282.jCljzt67zP29x2WtWs_Q_gzjM3RUTY8aE3732K9bdmM
+ replay-tabs-home-filters-banner--event-match-scope-only-during-recording--light:
+ hash: v1.k794b7964.f06605f72c3416040beb8cb5369cfc077a646d5ff1aa4d21f308a28dce99efdb.Qw2htfdPddy7jYaOKZ7iN9wptxD8bnUJElP6jcrzvUg
+ replay-tabs-home-filters-banner--event-match-scope-whole-session--dark:
+ hash: v1.k794b7964.1d2a4083393db09a6e18bfd5c96d9d0a1df9ad497d5ee77e6bb47307fbf43a84.tVACRDwJfqOxsA4HI-1lRxSRpcGXNCSCHu5OSlbYZFw
+ replay-tabs-home-filters-banner--event-match-scope-whole-session--light:
+ hash: v1.k794b7964.259486a3df29e32bad864a9e06079cdb8a1f6a1cb0dc5a4a77a56266ecead44e.VckaQWTQZOhQhLXAB_kkZ0RYpUtcSSTOb1f1pKmlKwQ
replay-tabs-home-filters-banner--page-filter-nudge--dark:
hash: v1.k794b7964.ef10ad389f863bfe246e69dc7bb0c74c3735cede108e2d373aa5b8338446b424.ewXseA-JwXOXnnzhCjOxwWoEzJiNIQsRDSepEBEsJ2Q
replay-tabs-home-filters-banner--page-filter-nudge--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 4ebf45c6a141..8a39bfff4a41 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -489,6 +489,7 @@ export const FEATURE_FLAGS = {
RECORDINGS_PLAYER_EVENT_PROPERTY_EXPANSION: 'recordings-player-event-property-expansion', // owner: @pauldambra #team-replay
REMOTE_CONFIG: 'remote-config', // owner: #team-platform-features
REPLAY_COLLAPSE_INSPECTOR_ITEMS: 'replay-collapse-inspector-items', // owner: @fasyy612 #team-replay
+ REPLAY_EVENT_MATCH_SCOPE: 'replay-event-match-scope', // owner: @pauldambra #team-replay, shows the "Match the whole session / only during recording" filter select
REPLAY_FILTERS_REDESIGN: 'replay-filters-redesign', // owner: @ksvat #team-replay
REPLAY_NEGATIVE_EVENT_FILTERS: 'replay-negative-event-filters', // owner: @arnohillen #team-replay
REPLAY_PLAYLIST_SURFACING_SCORE: 'replay-playlist-surfacing-score', // owner: #team-replay
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index ab390d8a2b60..d29c74b9f38c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -50237,6 +50237,12 @@
},
"type": "array"
},
+ "event_match_scope": {
+ "default": "session",
+ "description": "Where a filter that is evaluated against events must match. 'session' (default) matches an event anywhere in the session, including before the recording started or after it ended. 'recording' only matches events from one minute before the recording starts until one minute after it ends. This applies to every filter the events table answers: events, actions, event properties, and, when the project resolves them on events, person, group, and cohort properties.",
+ "enum": ["recording", "session"],
+ "type": "string"
+ },
"events": {
"items": {
"type": "object"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 402c605b4423..beb6e1905728 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -806,6 +806,15 @@ export interface RecordingsQuery extends DataNode<RecordingsQueryResponse> {
* @default "AND"
* */
operand?: FilterLogicalOperator
+ /**
+ * Where a filter that is evaluated against events must match. 'session' (default) matches an event
+ * anywhere in the session, including before the recording started or after it ended. 'recording' only
+ * matches events from one minute before the recording starts until one minute after it ends.
+ * This applies to every filter the events table answers: events, actions,
+ * event properties, and, when the project resolves them on events, person, group, and cohort properties.
+ * @default "session"
+ */
+ event_match_scope?: 'recording' | 'session'
session_ids?: string[]
/** Exclude recordings already viewed by the current user ('current-user'), by any team member ('any-user'), or none (default). Applied server-side so pagination and the result cursor operate on the filtered set. */
hide_viewed_recordings?: 'current-user' | 'any-user' | null
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingEventMatchScopeSelect.tsx b/frontend/src/scenes/session-recordings/filters/RecordingEventMatchScopeSelect.tsx
new file mode 100644
index 000000000000..2ab6a68a68db
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/filters/RecordingEventMatchScopeSelect.tsx
@@ -0,0 +1,65 @@
+import { LemonSelect } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { RecordingUniversalFilters } from '~/types'
+
+type EventMatchScope = NonNullable<RecordingUniversalFilters['event_match_scope']>
+
+function ScopeOption({ title, description }: { title: string; description: string }): JSX.Element {
+ return (
+ <div className="p-1">
+ <div className="font-bold">{title}</div>
+ <div className="font-normal">{description}</div>
+ </div>
+ )
+}
+
+export function RecordingEventMatchScopeSelect({
+ filters,
+ setFilters,
+}: {
+ filters: RecordingUniversalFilters
+ setFilters: (filters: Partial<RecordingUniversalFilters>) => void
+}): JSX.Element | null {
+ const enabled = useFeatureFlag('REPLAY_EVENT_MATCH_SCOPE')
+ if (!enabled) {
+ return null
+ }
+
+ const value: EventMatchScope = filters.event_match_scope ?? 'session'
+
+ return (
+ <LemonSelect<EventMatchScope>
+ className="ml-2"
+ size="small"
+ value={value}
+ onChange={(scope) => setFilters({ event_match_scope: scope === 'recording' ? 'recording' : undefined })}
+ options={[
+ {
+ label: 'in the whole session',
+ value: 'session',
+ labelInMenu: (
+ <ScopeOption
+ title="In the whole session"
+ description="Events count wherever they happen in the session, including before the recording started or after it ended"
+ />
+ ),
+ },
+ {
+ label: 'only during recording',
+ value: 'recording',
+ labelInMenu: (
+ <ScopeOption
+ title="Only during recording"
+ description="Events count from one minute before the recording starts until one minute after it ends"
+ />
+ ),
+ },
+ ]}
+ optionTooltipPlacement="bottom-start"
+ dropdownMatchSelectWidth={false}
+ data-attr="session-recordings-event-match-scope"
+ />
+ )
+}
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
index 70d2d33c4d28..ad758c3b600e 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
@@ -104,6 +104,33 @@ export const PageFilterNudge: Story = {
parameters: withPageFilter([{ type: 'event', key: '$current_url', operator: 'icontains', value: '/pricing' }]),
}
+const withEventMatchScope = (event_match_scope: 'recording' | undefined): Record<string, any> => ({
+ featureFlags: [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE],
+ pageUrl: combineUrl(urls.replay(), {
+ showFilters: true,
+ filters: {
+ date_from: '-3d',
+ date_to: null,
+ filter_test_accounts: false,
+ event_match_scope,
+ duration: [{ type: 'recording', key: 'duration', value: 1, operator: 'gt' }],
+ filter_group: {
+ type: 'AND',
+ values: [{ type: 'AND', values: [{ id: '$pageview', name: '$pageview', type: 'events' }] }],
+ },
+ },
+ }).url,
+ testOptions: { waitForSelector: '[data-attr="session-recordings-event-match-scope"]' },
+})
+
+export const EventMatchScopeWholeSession: Story = {
+ parameters: withEventMatchScope(undefined),
+}
+
+export const EventMatchScopeOnlyDuringRecording: Story = {
+ parameters: withEventMatchScope('recording'),
+}
+
export const TemplatesTab: Story = {
parameters: {
featureFlags: { [FEATURE_FLAGS.REPLAY_TEMPLATES_IN_FILTERS_PANEL_EXPERIMENT]: 'test' },
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
index 5e991bda0670..7235b081fbff 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
@@ -52,6 +52,7 @@ import { getProjectEventExistence } from 'lib/utils/getAppContext'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'
import { MaxTool } from 'scenes/max/MaxTool'
+import { RecordingEventMatchScopeSelect } from 'scenes/session-recordings/filters/RecordingEventMatchScopeSelect'
import { TimestampFormatToLabel, hasPageFilter } from 'scenes/session-recordings/utils'
import { urls } from 'scenes/urls'
@@ -891,40 +892,43 @@ export const ReplayFiltersTab = ({
)}
</div>
)}
- <div className="flex items-center py-2 justify-between px-2">
- <AndOrFilterSelect
- // Reflect the effective operand, not just the outer group: legacy saved filters can
- // carry the match-any on the inner group while the outer stays AND. Toggling syncs
- // both below, so interacting normalizes the structure.
- value={deriveOperand(filters.filter_group)}
- onChange={(type) => {
- // Clicking the already-effective operand is a no-op — don't rewrite the
- // group or mark the saved filter dirty just because the displayed value
- // came from a legacy inner group.
- if (type === deriveOperand(filters.filter_group)) {
- return
- }
+ <div className="flex flex-wrap items-center py-2 justify-between px-2 gap-y-2">
+ <div className="flex flex-wrap items-center gap-y-2">
+ <AndOrFilterSelect
+ // Reflect the effective operand, not just the outer group: legacy saved filters can
+ // carry the match-any on the inner group while the outer stays AND. Toggling syncs
+ // both below, so interacting normalizes the structure.
+ value={deriveOperand(filters.filter_group)}
+ onChange={(type) => {
+ // Clicking the already-effective operand is a no-op — don't rewrite the
+ // group or mark the saved filter dirty just because the displayed value
+ // came from a legacy inner group.
+ if (type === deriveOperand(filters.filter_group)) {
+ return
+ }
- let values = filters.filter_group.values
+ let values = filters.filter_group.values
- // set the type on the nested child when only using a single filter group
- const hasSingleGroup = values.length === 1
- if (hasSingleGroup) {
- const group = values[0] as UniversalFiltersGroup
- values = [{ ...group, type }]
- }
+ // set the type on the nested child when only using a single filter group
+ const hasSingleGroup = values.length === 1
+ if (hasSingleGroup) {
+ const group = values[0] as UniversalFiltersGroup
+ values = [{ ...group, type }]
+ }
- setFilters({
- filter_group: {
- type: type,
- values: values,
- },
- })
- }}
- topLevelFilter={true}
- suffix={['filter', 'filters']}
- size="small"
- />
+ setFilters({
+ filter_group: {
+ type: type,
+ values: values,
+ },
+ })
+ }}
+ topLevelFilter={true}
+ suffix={['filter', 'filters']}
+ size="small"
+ />
+ <RecordingEventMatchScopeSelect filters={filters} setFilters={setFilters} />
+ </div>
<div>
{compactActions ? (
resetButton
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
index f119f7d0b4d7..302d35cb30d8 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
@@ -236,10 +236,12 @@ describe('convertUniversalFiltersToRecordingsQuery ∘ recordingsQueryToUniversa
const query = rq({
experiment_exposure: { experiment_id: 42, variant: 'test' },
recommended_only: true,
+ event_match_scope: 'recording',
})
const back = roundTrip(query)
expect(back.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
expect(back.recommended_only).toBe(true)
+ expect(back.event_match_scope).toBe('recording')
})
})
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
index a0fa3553b2b8..f7a860db137a 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
@@ -157,6 +157,7 @@ export function convertUniversalFiltersToRecordingsQuery(universalFilters: Recor
comment_text,
filter_test_accounts: universalFilters.filter_test_accounts,
recommended_only: universalFilters.recommended_only,
+ event_match_scope: universalFilters.event_match_scope,
operand: deriveOperand(universalFilters.filter_group),
limit: universalFilters.limit,
session_ids: universalFilters.session_ids,
@@ -198,5 +199,6 @@ export function recordingsQueryToUniversalFilters(
// dropping it on the round-trip would silently widen the scanner to every recording.
experiment_exposure: query?.experiment_exposure,
recommended_only: query?.recommended_only,
+ event_match_scope: query?.event_match_scope,
}
}
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 06c3a1697850..387976ee4404 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -1304,6 +1304,45 @@ describe('sessionRecordingsPlaylistLogic', () => {
expect(logic.values.matchingEventsMatchType.matchType).toBe('none')
})
+
+ it.each(['events', 'actions'] as const)(
+ 'uses the effective scope for %s matching when flags change',
+ (type) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: false })
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: `match-scope-${type}`,
+ filters: {
+ ...DEFAULT_RECORDING_FILTERS,
+ event_match_scope: 'recording',
+ filter_group: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [{ id: type === 'events' ? '$pageview' : 1, name: '$pageview', type }],
+ },
+ ],
+ },
+ },
+ })
+ logic.mount()
+
+ const sessionMatch =
+ type === 'events'
+ ? { matchType: 'name', eventNames: ['$pageview'] }
+ : { matchType: 'backend', filters: expect.objectContaining({ event_match_scope: undefined }) }
+ expect(logic.values.matchingEventsMatchType).toEqual(sessionMatch)
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: true })
+ expect(logic.values.matchingEventsMatchType).toEqual({
+ matchType: 'backend',
+ filters: expect.objectContaining({ event_match_scope: 'recording' }),
+ })
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: false })
+ expect(logic.values.matchingEventsMatchType).toEqual(sessionMatch)
+ }
+ )
})
describe('resetting filters', () => {
@@ -2693,6 +2732,34 @@ describe('sessionRecordingsPlaylistLogic', () => {
).toEqual({ ...recommendedFilters, recommended_only: false })
})
+ it.each([
+ [true, 'recording'],
+ [false, undefined],
+ ])('with the event match scope flag %s a persisted recording scope becomes %s', (flagOn, expected) => {
+ const scopedFilters: RecordingUniversalFilters = { ...recommendedFilters, event_match_scope: 'recording' }
+ expect(
+ getEffectiveRecordingFilters(scopedFilters, {
+ [FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT]: 'test',
+ [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: flagOn,
+ }).event_match_scope
+ ).toBe(expected)
+ })
+
+ it.each([true, false])('reloads a saved recording scope when the flag becomes %s', async (enabled) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: !enabled })
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: `delayed-recording-scope-${enabled}`,
+ filters: { ...DEFAULT_RECORDING_FILTERS, event_match_scope: 'recording' },
+ })
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toDispatchActions(['loadSessionRecordingsSuccess'])
+
+ await expectLogic(logic, () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE]: enabled })
+ }).toDispatchActions(['loadSessionRecordings', 'loadSessionRecordingsSuccess'])
+ })
+
it('clears a persisted recommended filter for the control variant', async () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT]: 'control',
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index 387416de2096..acd9cce43fd9 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -228,13 +228,23 @@ export const DEFAULT_RECORDING_FILTERS: RecordingUniversalFilters = {
order_direction: 'DESC',
}
+/**
+ * Drops flag-gated filter settings the current user cannot see, so a persisted filter (a saved filter,
+ * a URL, a collection) cannot keep applying a setting after its flag is turned off.
+ */
export const getEffectiveRecordingFilters = (
filters: RecordingUniversalFilters,
featureFlags: FeatureFlagsSet
-): RecordingUniversalFilters =>
- featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] === 'test'
- ? filters
- : { ...filters, recommended_only: false }
+): RecordingUniversalFilters => {
+ let effective = filters
+ if (featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] !== 'test') {
+ effective = { ...effective, recommended_only: false }
+ }
+ if (!featureFlags[FEATURE_FLAGS.REPLAY_EVENT_MATCH_SCOPE] && effective.event_match_scope !== undefined) {
+ effective = { ...effective, event_match_scope: undefined }
+ }
+ return effective
+}
export const getDefaultFilters = (
personUUID?: PersonUUID,
@@ -906,7 +916,10 @@ export interface sessionRecordingsPlaylistLogicMeta {
logicProps: (arg: any) => SessionRecordingPlaylistLogicProps
allowEventPropertyExpansion: (featureFlags: FeatureFlagsSet) => boolean
exposureSkipExperimentId: (filters: RecordingUniversalFilters) => number | undefined
- matchingEventsMatchType: (filters: RecordingUniversalFilters) => MatchingEventsMatchType
+ matchingEventsMatchType: (
+ filters: RecordingUniversalFilters,
+ featureFlags: FeatureFlagsSet
+ ) => MatchingEventsMatchType
activeSessionRecordingId: (
selectedRecordingId: string | null,
recordings: SessionRecordingType[],
@@ -1568,14 +1581,17 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
return {
setFeatureFlags: () => {
- if (!values.filters.recommended_only) {
+ if (values.filters.recommended_only) {
+ if (values.featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] === 'test') {
+ actions.loadSessionRecordings()
+ } else {
+ // The flag decides this one, so it is not a viewer edit.
+ actions.setFilters({ recommended_only: false }, false)
+ }
return
}
- if (values.featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] === 'test') {
+ if (values.filters.event_match_scope === 'recording') {
actions.loadSessionRecordings()
- } else {
- // The flag decides this one, so it is not a viewer edit.
- actions.setFilters({ recommended_only: false }, false)
}
},
loadAllRecordings: () => {
@@ -2066,11 +2082,12 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
],
matchingEventsMatchType: [
- (s) => [s.filters],
- (filters: RecordingUniversalFilters): MatchingEventsMatchType => {
- if (!filters) {
+ (s) => [s.filters, s.featureFlags],
+ (storedFilters: RecordingUniversalFilters, featureFlags: FeatureFlagsSet): MatchingEventsMatchType => {
+ if (!storedFilters) {
return { matchType: 'none' }
}
+ const filters = getEffectiveRecordingFilters(storedFilters, featureFlags)
const filterValues = filtersFromUniversalFilterGroups(filters)
@@ -2095,6 +2112,10 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
return { matchType: 'none' }
}
+ if (filters.event_match_scope === 'recording') {
+ return { matchType: 'backend', filters }
+ }
+
if (hasEvents && hasSimpleEventsFilters && simpleEventsFilters.length === eventFilters.length) {
return {
matchType: 'name',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 587ca750ab70..c0f09c1f035a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1633,6 +1633,7 @@ export interface RecordingUniversalFilters {
order_direction?: RecordingsQuery['order_direction']
limit?: RecordingsQuery['limit']
recommended_only?: boolean
+ event_match_scope?: RecordingsQuery['event_match_scope']
/**
* Server-resolved population narrowing (sessions of persons exposed to the experiment).
* Not part of `filter_group`, so the filter-pill editor neither renders nor edits it;
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 2d921780f572..4bed4d2a2bd8 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -496,7 +496,11 @@ class QueryTags(BaseModel):
# in-session exposure evidence, which adds a live events scan and a GLOBAL IN set on top of the
# population read. Separates that heavier read from a plain exposure listing in the query log.
experiment_exposures_in_session: Optional[bool] = None
- # Set on recordings-list reads with positive events-table filters, to compare the combined scan.
+ # Set on a recordings-list read whose event filters only match inside each recording's window.
+ # That path adds a GLOBAL JOIN on the per-recording bounds to every events subquery, so the tag
+ # separates its cost from the default session-scoped listing in the query log.
+ replay_event_match_scope: Optional[str] = None # "recording"; absent for the default session scope
+ # Set on recordings-list reads with positive events-table filters, in both scopes, to compare the combined scan.
replay_event_query_strategy: Optional[Literal["separate", "combined"]] = None
replay_event_filter_count: Optional[int] = None
replay_event_query_property_filter_count: Optional[int] = None
diff --git a/posthog/schema.py b/posthog/schema.py
index 9fb04934d82e..3f4772cf9328 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -110,6 +110,7 @@ from posthog.schema_enums import (
ErrorTrackingQueryIssueSeverity as ErrorTrackingQueryIssueSeverity,
ErrorTrackingReleasesOrderBy as ErrorTrackingReleasesOrderBy,
EvaluationRuntime as EvaluationRuntime,
+ EventMatchScope as EventMatchScope,
ExperimentMetricGoal as ExperimentMetricGoal,
ExperimentMetricMathType as ExperimentMetricMathType,
ExperimentMetricType as ExperimentMetricType,
@@ -28918,6 +28919,18 @@ class RecordingsQuery(BaseModel):
date_from: str | None = "-3d"
date_to: str | None = None
distinct_ids: list[str] | None = None
+ event_match_scope: EventMatchScope | None = Field(
+ default=EventMatchScope.SESSION,
+ description=(
+ "Where a filter that is evaluated against events must match. 'session'"
+ " (default) matches an event anywhere in the session, including before the"
+ " recording started or after it ended. 'recording' only matches events from"
+ " one minute before the recording starts until one minute after it ends."
+ " This applies to every filter the events table answers: events, actions,"
+ " event properties, and, when the project resolves them on events, person,"
+ " group, and cohort properties."
+ ),
+ )
events: list[dict[str, Any]] | None = None
experiment_exposure: RecordingsQueryExperimentExposureFilter | None = Field(
default=None,
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 7f67d3dc452c..31eddde64776 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2658,6 +2658,11 @@ class RecordingOrderDirection(StrEnum):
DESC = "DESC"
+class EventMatchScope(StrEnum):
+ RECORDING = "recording"
+ SESSION = "session"
+
+
class HideViewedRecordings(Enum):
CURRENT_USER = "current-user"
ANY_USER = "any-user"
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index 9e358dad96be..746337c67cf9 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -8,6 +8,7 @@ from opentelemetry import trace
from rest_framework.exceptions import PermissionDenied
from posthog.schema import (
+ EventMatchScope,
HogQLQueryModifiers,
PropertyOperator,
RecordingOrder,
@@ -287,6 +288,8 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
listing_tags: dict[str, Any] = {}
if in_session_narrowed:
listing_tags["experiment_exposures_in_session"] = True
+ if self._query.event_match_scope == EventMatchScope.RECORDING:
+ listing_tags["replay_event_match_scope"] = EventMatchScope.RECORDING.value
plan = self._event_match_plan
if plan is not None and plan.filter_count:
listing_tags["replay_event_query_strategy"] = plan.strategy
@@ -313,12 +316,18 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
# nothing to probe when the caller excluded against its own rows instead, where the scoped
# query is bounded by the ids it was given rather than by the cap.
if not self._skip_negative_blocklists:
- ReplayFiltersEventsSubQuery(
- self._team,
- self._query,
- self._allow_event_property_expansion,
- hogql_query_modifiers=self._hogql_query_modifiers,
- ).check_negative_blocklist_truncation()
+ # Under recording scope the probe re-runs the blocklist scan with its bounds join, so it
+ # carries the scope tag too; without it the query log undercounts what the scope costs.
+ probe_tags: dict[str, Any] = {}
+ if self._query.event_match_scope == EventMatchScope.RECORDING:
+ probe_tags["replay_event_match_scope"] = EventMatchScope.RECORDING.value
+ with tags_context(**probe_tags):
+ ReplayFiltersEventsSubQuery(
+ self._team,
+ self._query,
+ self._allow_event_property_expansion,
+ hogql_query_modifiers=self._hogql_query_modifiers,
+ ).check_negative_blocklist_truncation()
with tracer.start_as_current_span("SessionRecordingListFromQuery._data_to_return"):
next_cursor = None
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index 514aef2e845a..e86c17d48ce8 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -1,14 +1,16 @@
from collections.abc import Iterable
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Optional, cast
import posthoganalytics
+from dateutil.relativedelta import relativedelta
from prometheus_client import Counter
from rest_framework.exceptions import ValidationError
from posthog.schema import (
ActionsNode,
DataWarehouseNode,
+ EventMatchScope,
EventPropertyFilter,
EventsNode,
HogQLQueryModifiers,
@@ -18,7 +20,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
-from posthog.hogql.parser import parse_expr
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query, tracer
@@ -58,6 +60,8 @@ REPLAY_NEGATIVE_BLOCKLIST_TRUNCATED_COUNTER = Counter(
"A replay exclusion blocklist hit its row cap, so some sessions were not excluded from the results",
)
+# Allow for the delay between an event and the recorder's first or last snapshot.
+RECORDING_MATCH_MARGIN_MINUTES = 1
COMBINED_EVENT_FILTERS_FLAG = "replay-combined-event-filters"
EVENTS_SUBQUERY_ROW_LIMIT = 1_000_000
@@ -132,14 +136,75 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
self._resolve_group_properties = resolve_group_properties
self.emitted_sampled_subquery = False
- def _events_join(self, sample: bool = True) -> ast.JoinExpr:
+ def _events_join(self, sample: bool = True, scope_session_ids: list[str] | None = None) -> ast.JoinExpr:
join = ast.JoinExpr(table=ast.Field(chain=["events"]))
# Only positive session-selectors sample; a sampled exclusion blocklist would under-exclude.
if sample and self._sample_factor is not None:
join.sample = ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=self._sample_factor)))
self.emitted_sampled_subquery = True
+ if self._query.event_match_scope == EventMatchScope.RECORDING:
+ join.next_join = ast.JoinExpr(
+ # GLOBAL: the initiator builds the per-recording bounds once and ships them to each
+ # shard. Without it every shard would fan the replay scan out across the cluster again.
+ join_type="GLOBAL INNER JOIN",
+ table=self._recording_bounds_query(scope_session_ids=scope_session_ids),
+ alias="recording_bounds",
+ constraint=ast.JoinConstraint(
+ expr=parse_expr("recording_bounds.session_id = events.properties.$session_id"),
+ constraint_type="ON",
+ ),
+ )
return join
+ def _recording_bounds_query(self, scope_session_ids: list[str] | None = None) -> ast.SelectQuery:
+ session_ids = scope_session_ids if scope_session_ids is not None else self._query.session_ids
+ if session_ids is not None:
+ scope = parse_expr(
+ "s.session_id IN {session_ids} AND s.min_first_timestamp >= {date_from}",
+ placeholders={
+ "session_ids": ast.Constant(value=session_ids),
+ "date_from": ast.Constant(value=datetime.now(UTC) - relativedelta(years=5)),
+ },
+ )
+ else:
+ # Include adjacent segments because a recording can cross either date boundary. One day of
+ # slack covers the SDK's 24-hour session cap; a wider window would grow the GLOBAL-shipped
+ # bounds set for every query to cover only sessions no conforming SDK records.
+ scope = parse_expr(
+ "s.min_first_timestamp >= {date_from} AND s.min_first_timestamp <= {date_to}",
+ placeholders={
+ "date_from": ast.Constant(value=self.query_date_range.date_from() - timedelta(days=1)),
+ "date_to": ast.Constant(value=self.query_date_range.date_to() + timedelta(days=1)),
+ },
+ )
+ query = parse_select(
+ """
+ SELECT s.session_id AS session_id,
+ min(s.min_first_timestamp) AS window_start,
+ max(s.max_last_timestamp) AS window_end
+ FROM raw_session_replay_events AS s
+ WHERE {scope}
+ GROUP BY s.session_id
+ """,
+ placeholders={"scope": scope},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _recording_window_predicates(self) -> list[ast.Expr]:
+ if self._query.event_match_scope != EventMatchScope.RECORDING:
+ return []
+ return [
+ parse_expr(
+ "events.timestamp >= subtractMinutes(recording_bounds.window_start, {margin})",
+ placeholders={"margin": ast.Constant(value=RECORDING_MATCH_MARGIN_MINUTES)},
+ ),
+ parse_expr(
+ "events.timestamp <= addMinutes(recording_bounds.window_end, {margin})",
+ placeholders={"margin": ast.Constant(value=RECORDING_MATCH_MARGIN_MINUTES)},
+ ),
+ ]
+
@staticmethod
def _event_predicates(
entities: Iterable[EventsNode | ActionsNode | DataWarehouseNode], team: Team
@@ -328,6 +393,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
# true and reach the GROUP BY. The caller matches this against the replay
# table's non-nullable session_id, which rejects a NULL in the set.
ast.Call(name="notEmpty", args=[_event_session_id_field()]),
+ *self._recording_window_predicates(),
]
),
group_by=[_event_session_id_field()], # DISTINCT session_id
@@ -643,7 +709,13 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
def get_session_id_match_plan(self, allow_combined_filters: bool = False) -> SessionIdMatchPlan:
gathered_exprs, hybrid_query = self._gathered_exprs(union_entities=False)
eligible = allow_combined_filters and self._can_combine_session_filters(len(gathered_exprs))
- combined = eligible and self._combined_filters_enabled()
+ # Recording scope adds a GLOBAL JOIN on the per-recording bounds to every events subquery, and
+ # ClickHouse ships and builds that bounds set once per subquery. Separate queries would ship it
+ # once per filter, so eligible filters always take the single combined scan under this scope.
+ # The combined flag still A/B-tests the strategies where almost all traffic is: session scope.
+ combined = eligible and (
+ self._query.event_match_scope == EventMatchScope.RECORDING or self._combined_filters_enabled()
+ )
queries = (
[self._combined_session_query(gathered_exprs)]
if combined
@@ -694,7 +766,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
)
return ast.SelectQuery(
select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],
- select_from=self._events_join(sample=False),
+ select_from=self._events_join(sample=False, scope_session_ids=session_ids),
where=where,
group_by=[_event_session_id_field()],
# A session id can only be returned once, so the input bounds the output.
@@ -855,6 +927,8 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
)
)
+ exprs += self._recording_window_predicates()
+
return ast.And(exprs=exprs)
def _having_predicates(self) -> ast.Expr:
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index 1c2585439721..fa0862b6d1c7 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -30,9 +30,11 @@ from tenacity import retry, stop_after_attempt, wait_exponential
from posthog.schema import ActionsNode, EventsNode, PersonsOnEventsMode, RecordingsQuery
+from posthog.hogql import ast
from posthog.hogql.ast import SelectQuery
from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.visitor import TraversingVisitor
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
@@ -877,9 +879,12 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("enabled", True, {}, {}, True, "combined", True),
- ("disabled", False, {}, {}, True, "separate", True),
- ("unavailable", None, {}, {}, True, "separate", True),
+ ("enabled", True, {"event_match_scope": "session"}, {}, True, "combined", True),
+ ("disabled", False, {"event_match_scope": "session"}, {}, True, "separate", True),
+ ("unavailable", None, {"event_match_scope": "session"}, {}, True, "separate", True),
+ # Recording scope pays a GLOBAL bounds join per subquery, so eligible filters combine
+ # into one scan without consulting the flag.
+ ("recording_scope_combines_without_the_flag", False, {}, {}, True, "combined", True),
("negative_property", True, {"category_operator": "is_not"}, {}, True, "separate", False),
("person_property", True, {"person_property": True}, {}, True, "separate", False),
("sampled", True, {}, {"sample_factor": 0.5}, True, "separate", False),
@@ -906,6 +911,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
expected_eligible: bool,
) -> None:
query: dict[str, Any] = {
+ "event_match_scope": shape.get("event_match_scope", "recording"),
"events": [
{
"id": "view_item",
@@ -933,11 +939,72 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
assert (plan.strategy, plan.combined_eligible) == (expected_strategy, expected_eligible)
if expected_strategy == "combined":
assert len(plan.queries) == 1
- if expected_eligible:
+ # Recording scope decides without the flag, so only eligible session-scope plans consult it.
+ if expected_eligible and query["event_match_scope"] == "session":
assert evaluate.call_args.args[0] == "replay-combined-event-filters"
else:
evaluate.assert_not_called()
+ @parameterized.expand([("recording", True), ("session", False)])
+ def test_the_recording_bounds_join_and_its_window_predicates_travel_together(
+ self, scope: str, expects_scope: bool
+ ) -> None:
+ # The join and the window predicates come from different methods, and a subquery carrying the
+ # join without the predicates matches events outside the recording again — silently, since the
+ # join alone still returns plausible results. Every events subquery must hold both or neither.
+ def bounds_join_aliases(query: ast.SelectQuery) -> list[str]:
+ aliases = []
+ join = query.select_from
+ while join is not None:
+ if join.alias:
+ aliases.append(join.alias)
+ join = join.next_join
+ return aliases
+
+ def bounds_fields(node: ast.AST) -> set[str]:
+ fields: set[str] = set()
+
+ class Collector(TraversingVisitor):
+ def visit_field(self, field: ast.Field) -> None:
+ if field.chain and field.chain[0] == "recording_bounds":
+ fields.add(str(field.chain[-1]))
+
+ Collector().visit(node)
+ return fields
+
+ query: dict[str, Any] = {
+ "event_match_scope": scope,
+ "operand": "AND",
+ "events": [
+ # A negated entity, so the plan stays on the separate path and the blocklist exists.
+ {"id": "view_item", "type": "events", "order": 0},
+ {"id": "purchase", "type": "events", "order": 1, "negation": True},
+ ],
+ "properties": [{"type": "event", "key": "source", "operator": "exact", "value": "search"}],
+ }
+ builder = ReplayFiltersEventsSubQuery(team=self.team, query=RecordingsQuery.model_validate(query))
+ subqueries: list[ast.SelectQuery] = [
+ *builder.get_session_id_match_plan(allow_combined_filters=True).queries,
+ ]
+ blocklist = builder.get_negative_blocklist_query()
+ assert blocklist is not None
+ subqueries.append(blocklist)
+ excluded = builder.get_excluded_sessions_query(["a-session-id"])
+ assert excluded is not None
+ subqueries.append(excluded)
+
+ assert len(subqueries) >= 4
+ for subquery in subqueries:
+ joined = "recording_bounds" in bounds_join_aliases(subquery)
+ assert subquery.where is not None
+ referenced = bounds_fields(subquery.where)
+ if expects_scope:
+ assert joined, subquery
+ assert referenced == {"window_start", "window_end"}, subquery
+ else:
+ assert not joined, subquery
+ assert referenced == set(), subquery
+
@parameterized.expand(
[
("events without a type", "events", None, EventsNode, "event_entities"),
@@ -2934,16 +3001,21 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
[],
)
+ # Session 2 adds the item after its recording ends, so only whole-session matching counts it.
@parameterized.expand(
[
- ("AND", False, [0, 1, 2, 3]),
- ("AND", True, [0, 1, 2]),
- ("OR", False, [0, 1, 2, 3]),
- ("OR", True, [0, 1, 2, 3, 4]),
+ ("recording", "AND", False, [0, 1, 3]),
+ ("recording", "AND", True, [0, 1]),
+ ("recording", "OR", False, [0, 1, 2, 3]),
+ ("recording", "OR", True, [0, 1, 2, 3, 4]),
+ ("session", "AND", False, [0, 1, 2, 3]),
+ ("session", "AND", True, [0, 1, 2]),
+ ("session", "OR", False, [0, 1, 2, 3]),
+ ("session", "OR", True, [0, 1, 2, 3, 4]),
]
)
def test_combined_event_filters_preserve_results_and_cursors(
- self, operand: str, with_properties: bool, expected_indexes: list[int]
+ self, scope: str, operand: str, with_properties: bool, expected_indexes: list[int]
) -> None:
sessions = [str(uuid7()) for _ in range(5)]
for index, session_id in enumerate(sessions):
@@ -2971,6 +3043,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
properties={"$session_id": session_id, **properties},
)
filters: dict[str, Any] = {
+ "event_match_scope": scope,
"operand": operand,
"events": [
{
@@ -3010,8 +3083,10 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
after = page.next_cursor
assert after is not None
assert not pages[-1].has_more_recording
+ # Recording scope combines without the flag, to pay its GLOBAL bounds join only once.
+ expected_strategy = "combined" if enabled or scope == "recording" else "separate"
assert any(
- call.kwargs.get("replay_event_query_strategy") == ("combined" if enabled else "separate")
+ call.kwargs.get("replay_event_query_strategy") == expected_strategy
and call.kwargs.get("replay_event_filter_count") == (3 if with_properties else 2)
and call.kwargs.get("replay_event_query_property_filter_count") == (2 if with_properties else 0)
and call.kwargs.get("replay_combined_event_query_eligible") is True
@@ -3023,6 +3098,150 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
expected = [sessions[index] for index in reversed(expected_indexes)]
assert [row["session_id"] for page in pages_by_strategy[1] for row in page.results] == expected
+ @parameterized.expand(
+ [
+ ("session_scope_matches_before_the_recording", "session", relativedelta(minutes=-10), True),
+ ("recording_scope_rejects_before_the_recording", "recording", relativedelta(minutes=-10), False),
+ ("recording_scope_allows_the_margin_before_the_recording", "recording", relativedelta(seconds=-30), True),
+ ("recording_scope_matches_inside_the_recording", "recording", relativedelta(minutes=2), True),
+ ("recording_scope_rejects_after_the_recording", "recording", relativedelta(minutes=10), False),
+ ]
+ )
+ def test_event_match_scope_bounds_event_filters_to_the_recording(
+ self, _name: str, scope: str, event_offset: relativedelta, matches: bool
+ ) -> None:
+ distinct_id = f"event-match-scope-user-{uuid4()}"
+ create_person(team=self.team, distinct_ids=[distinct_id], properties={"email": "bla"})
+ session_id = f"event-match-scope-session-{uuid4()}"
+
+ produce_replay_summary(
+ distinct_id=distinct_id,
+ session_id=session_id,
+ first_timestamp=self.an_hour_ago,
+ last_timestamp=self.an_hour_ago + relativedelta(minutes=5),
+ team_id=self.team.id,
+ )
+ create_event(
+ team=self.team,
+ distinct_id=distinct_id,
+ timestamp=self.an_hour_ago + event_offset,
+ event_name="$pageview",
+ properties={"$session_id": session_id},
+ )
+
+ self._assert_query_matches_session_ids(
+ {
+ "events": [{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}],
+ "event_match_scope": scope,
+ },
+ [session_id] if matches else [],
+ )
+
+ @parameterized.expand(
+ [
+ ("session_scope_excludes_on_an_event_before_the_recording", "session", False),
+ ("recording_scope_ignores_an_event_before_the_recording", "recording", True),
+ ]
+ )
+ def test_event_match_scope_applies_to_negated_events(self, _name: str, scope: str, is_listed: bool) -> None:
+ distinct_id = f"event-match-scope-negation-user-{uuid4()}"
+ create_person(team=self.team, distinct_ids=[distinct_id], properties={"email": "bla"})
+ session_id = f"event-match-scope-negation-session-{uuid4()}"
+
+ produce_replay_summary(
+ distinct_id=distinct_id,
+ session_id=session_id,
+ first_timestamp=self.an_hour_ago,
+ last_timestamp=self.an_hour_ago + relativedelta(minutes=5),
+ team_id=self.team.id,
+ )
+ create_event(
+ team=self.team,
+ distinct_id=distinct_id,
+ timestamp=self.an_hour_ago - relativedelta(minutes=10),
+ event_name="purchase",
+ properties={"$session_id": session_id},
+ )
+
+ self._assert_query_matches_session_ids(
+ {
+ "events": [{"id": "purchase", "type": "events", "order": 0, "name": "purchase", "negation": True}],
+ "event_match_scope": scope,
+ },
+ [session_id] if is_listed else [],
+ )
+
+ @parameterized.expand([(False,), (True,)])
+ def test_event_match_scope_includes_segments_across_the_date_boundary(self, negation: bool) -> None:
+ session_id = str(uuid4())
+ midnight = self.an_hour_ago.replace(hour=0, minute=0)
+ for start, end in [(-10, -1), (1, 10)]:
+ produce_replay_summary(
+ team_id=self.team.id,
+ session_id=session_id,
+ distinct_id="boundary-user",
+ first_timestamp=midnight + relativedelta(minutes=start),
+ last_timestamp=midnight + relativedelta(minutes=end),
+ ensure_analytics_event_in_session=False,
+ )
+ create_event(
+ team=self.team,
+ distinct_id="boundary-user",
+ timestamp=midnight + relativedelta(minutes=5),
+ event_name="purchase",
+ properties={"$session_id": session_id},
+ )
+ self._assert_query_matches_session_ids(
+ {
+ "date_from": (midnight - relativedelta(days=1)).isoformat(),
+ "date_to": (midnight - relativedelta(seconds=1)).isoformat(),
+ "event_match_scope": "recording",
+ "events": [{"id": "purchase", "type": "events", "order": 0, "negation": negation}],
+ },
+ [] if negation else [session_id],
+ )
+
+ @parameterized.expand(
+ [
+ ("session_scope_matches_a_person_property_before_the_recording", "session", True),
+ ("recording_scope_needs_the_carrying_event_inside_the_recording", "recording", False),
+ ]
+ )
+ def test_event_match_scope_applies_to_person_properties_resolved_on_events(
+ self, _name: str, scope: str, matches: bool
+ ) -> None:
+ with self.settings(PERSON_ON_EVENTS_V2_OVERRIDE=True):
+ assert self.team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ distinct_id = f"event-match-scope-person-user-{uuid4()}"
+ create_person(team=self.team, distinct_ids=[distinct_id], properties={"email": "[email protected]"})
+ session_id = f"event-match-scope-person-session-{uuid4()}"
+
+ produce_replay_summary(
+ distinct_id=distinct_id,
+ session_id=session_id,
+ first_timestamp=self.an_hour_ago,
+ last_timestamp=self.an_hour_ago + relativedelta(minutes=5),
+ team_id=self.team.id,
+ ensure_analytics_event_in_session=False,
+ )
+ create_event(
+ team=self.team,
+ distinct_id=distinct_id,
+ timestamp=self.an_hour_ago - relativedelta(minutes=10),
+ event_name="$pageview",
+ properties={"$session_id": session_id},
+ )
+
+ self._assert_query_matches_session_ids(
+ {
+ "properties": [
+ {"key": "email", "value": ["[email protected]"], "operator": "exact", "type": "person"}
+ ],
+ "event_match_scope": scope,
+ },
+ [session_id] if matches else [],
+ )
+
@also_test_with_materialized_columns(event_properties=["$current_url", "$browser"], person_properties=["email"])
@snapshot_clickhouse_queries
def test_event_filter_with_hogql_properties(self):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b2b217aab48a..105f9e6b739a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40873,6 +40873,14 @@ export namespace Schemas {
matches: EventMatch[];
}
+ export type EventMatchScope = typeof EventMatchScope[keyof typeof EventMatchScope];
+
+
+ export const EventMatchScope = {
+ Recording: 'recording',
+ Session: 'session',
+ } as const;
+
/**
* * `DateTime` - DateTime
* * `String` - String
@@ -54288,6 +54296,8 @@ export namespace Schemas {
date_from?: string | null;
date_to?: string | null;
distinct_ids?: string[] | null;
+ /** Where a filter that is evaluated against events must match. 'session' (default) matches an event anywhere in the session, including before the recording started or after it ended. 'recording' only matches events from one minute before the recording starts until one minute after it ends. This applies to every filter the events table answers: events, actions, event properties, and, when the project resolves them on events, person, group, and cohort properties. */
+ event_match_scope?: EventMatchScope | null;
events?: RecordingsQueryEvents;
/** Only sessions of persons exposed to this experiment, each ending at or after the person's first exposure as the experiment's exposure criteria count it. Resolved server-side from the experiment, so it links sessions even when the exposure events themselves carry no session id (e.g. server-side SDKs). Composes with the query's date range like any other filter, so set date_from to the experiment's start (or earlier) to cover the full run: the default window only reaches back a few days. */
experiment_exposure?: RecordingsQueryExperimentExposureFilter | null;