: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): support excluding sessions by event and action filters (#72943)
Arno Hillen988c9031bb93
diff --git a/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx b/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsxindex 2d19791421a7..dfb3a5477e60 100644--- a/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx+++ b/frontend/src/lib/components/UniversalFilters/UniversalFilterButton.tsx@@ -17,7 +17,7 @@ import { ActionFilter, AnyPropertyFilter, FeaturePropertyFilter, UniversalFilterimport { EntityFilterInfo } from '../EntityFilterInfo'import { formatPropertyLabel } from '../PropertyFilters/utils'-import { isActionFilter, isEditableFilter, isEventFilter, isFeatureFlagFilter } from './utils'+import { isActionFilter, isEditableFilter, isEntityFilter, isEventFilter, isFeatureFlagFilter } from './utils'export interface UniversalFilterButtonProps {onClick?: () => void@@ -26,10 +26,11 @@ export interface UniversalFilterButtonProps {filter: UniversalFilterValuedisabledReason?: stringclassName?: string+ clickable?: boolean}export const UniversalFilterButton = React.forwardRef<HTMLElement, UniversalFilterButtonProps>(- function UniversalFilterButton({ onClick, onClose, filter, className }, ref): JSX.Element {+ function UniversalFilterButton({ onClick, onClose, filter, className, clickable = false }, ref): JSX.Element {const closable = onClose !== undefinedconst isEditable = isEditableFilter(filter)@@ -39,14 +40,17 @@ export const UniversalFilterButton = React.forwardRef<HTMLElement, UniversalFiltconst button = (<divref={ref as any}- onClick={isEditable ? onClick : undefined}+ onClick={isEditable || clickable ? onClick : undefined}className={clsx('UniversalFilterButton inline-flex items-center', className, {- 'UniversalFilterButton--clickable': isEditable,+ 'UniversalFilterButton--clickable': isEditable || clickable,'UniversalFilterButton--closeable': closable,'ph-no-capture': true,})}><div className="flex items-center flex-1 truncate gap-1">+ {isEntityFilter(filter) && filter.negation && (+ <span className="shrink-0 text-muted">did not perform</span>+ )}{isEvent ? (<EventLabel filter={filter} onClick={onClick} />) : isAction ? (diff --git a/frontend/src/lib/components/UniversalFilters/UniversalFilters.negation.test.tsx b/frontend/src/lib/components/UniversalFilters/UniversalFilters.negation.test.tsxnew file mode 100644index 000000000000..cf3e22f15253--- /dev/null+++ b/frontend/src/lib/components/UniversalFilters/UniversalFilters.negation.test.tsx@@ -0,0 +1,92 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { Provider } from 'kea'++import { initKeaTests } from '~/test/init'+import { ActionFilter, EntityTypes, FilterLogicalOperator, UniversalFiltersGroup } from '~/types'++import { TaxonomicFilterGroupType } from '../TaxonomicFilter/types'+import UniversalFilters from './UniversalFilters'++// Stub the taxonomic picker so the "change event" flow can be exercised without+// pinning taxonomic list internals or mocking its API calls.+jest.mock('../TaxonomicFilter/TaxonomicFilter', () => {+ const React = require('react')+ return {+ TaxonomicFilter: ({ onChange }: { onChange: (group: any, value: any, item: any) => void }): JSX.Element =>+ React.createElement(+ 'button',+ { onClick: () => onChange({ type: 'events' }, 'purchase', { name: 'purchase' }) },+ 'mock taxonomic option: purchase'+ ),+ }+})++describe('UniversalFilters entity negation', () => {+ const eventFilter: ActionFilter = { id: '$pageview', name: '$pageview', type: EntityTypes.EVENTS, properties: [] }++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ function renderValue(+ allowEntityNegation: boolean,+ onChange: jest.Mock,+ filter: ActionFilter = eventFilter+ ): HTMLElement {+ const group: UniversalFiltersGroup = { type: FilterLogicalOperator.And, values: [filter] }+ const { container } = render(+ <Provider>+ <UniversalFilters+ rootKey="negation-test"+ group={group}+ onChange={jest.fn()}+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}+ >+ <UniversalFilters.Value+ index={0}+ filter={filter}+ onChange={onChange}+ allowEntityNegation={allowEntityNegation}+ />+ </UniversalFilters>+ </Provider>+ )+ return container+ }++ async function openChipPopover(container: HTMLElement): Promise<void> {+ const chipButton = container.querySelector('.UniversalFilterButton button')+ expect(chipButton).not.toBeNull()+ await userEvent.click(chipButton as Element)+ }++ it.each([[true], [false]])('allowEntityNegation=%s controls the negation toggle', async (allowEntityNegation) => {+ const onChange = jest.fn()+ const container = renderValue(allowEntityNegation, onChange)+ await openChipPopover(container)+ if (allowEntityNegation) {+ await userEvent.click(screen.getByText('Did not perform'))+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ negation: true }))+ } else {+ expect(screen.queryByText('Did not perform')).toBeNull()+ }+ })++ it('keeps negation when changing the event', async () => {+ const onChange = jest.fn()+ const container = renderValue(true, onChange, { ...eventFilter, negation: true })+ await openChipPopover(container)+ await userEvent.click(screen.getByText('Change event'))+ await userEvent.click(screen.getByText('mock taxonomic option: purchase'))+ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'purchase', name: 'purchase', properties: [], negation: true })+ )+ })+})diff --git a/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx b/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsxindex f5c3280833d4..ce4fc0f81126 100644--- a/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx+++ b/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx@@ -2,7 +2,14 @@ import { BindLogic, useActions, useValues } from 'kea'import { useState } from 'react'import { IconPlusSmall } from '@posthog/icons'-import { LemonButton, LemonButtonProps, LemonDivider, LemonDropdown, Popover } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonButtonProps,+ LemonDivider,+ LemonDropdown,+ LemonSegmentedButton,+ Popover,+} from '@posthog/lemon-ui'import { OperatorValueSelectProps } from 'lib/components/PropertyFilters/components/OperatorValueSelect'import { taxonomicFilterGroupTypeToEntityType } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'@@ -22,7 +29,7 @@ import {} from '../TaxonomicFilter/types'import { UniversalFilterButton } from './UniversalFilterButton'import { universalFiltersLogic } from './universalFiltersLogic'-import { isEditableFilter, isEventFilter } from './utils'+import { isActionFilter, isEditableFilter, isEntityFilter, isEventFilter } from './utils'export type UniversalFiltersProps = {rootKey: string@@ -92,6 +99,7 @@ const Value = ({metadataSource,className,operatorAllowlist,+ allowEntityNegation = false,}: {index: numberfilter: UniversalFilterValue@@ -101,15 +109,44 @@ const Value = ({metadataSource?: AnyDataNodeclassName?: stringoperatorAllowlist?: OperatorValueSelectProps['operatorAllowlist']+ allowEntityNegation?: boolean}): JSX.Element => {const { rootKey, taxonomicPropertyFilterGroupTypes, endpointFilters } = useValues(universalFiltersLogic)const isEvent = isEventFilter(filter)+ const isAction = isActionFilter(filter)const isEditable = isEditableFilter(filter)const [open, setOpen] = useState<boolean>(isEditable && initiallyOpen)const [changingEvent, setChangingEvent] = useState<boolean>(false)+ // allowEntityNegation gates only the creation of new negations. Existing negation values+ // keep rendering (in UniversalFilterButton) and keep evaluating (backend applies them+ // unconditionally), so a feature flag rollback never silently flips "did not perform X"+ // back to "performed X" on saved filters.+ const negationSelect =+ allowEntityNegation && isEntityFilter(filter) ? (+ <div className="px-2 py-1" data-attr="universal-filters-entity-negation">+ <LemonSegmentedButton+ size="xsmall"+ value={filter.negation ? 'exclude' : 'include'}+ onChange={(value) => onChange({ ...filter, negation: value === 'exclude' })}+ options={[+ {+ value: 'include',+ label: 'Performed',+ 'data-attr': 'universal-filters-entity-negation-include',+ },+ {+ value: 'exclude',+ label: 'Did not perform',+ 'data-attr': 'universal-filters-entity-negation-exclude',+ },+ ]}+ />+ </div>+ ) : null+const pageKey = `${rootKey}.filter_${index}`const handleChangeEvent = (@@ -117,6 +154,9 @@ const Value = ({value: TaxonomicFilterValue,item: any): void => {+ // changing the event intentionally resets properties, but negation belongs to the+ // chip rather than the event, so an exclusion must stay an exclusion+ const negation = isEntityFilter(filter) ? filter.negation : undefined// Keyword shortcut (e.g. "Click (autocapture)"): set the event AND attach its// $event_type property filter, replacing any properties the previous event had.if (isQuickFilterItem(item) && item.eventName) {@@ -125,13 +165,14 @@ const Value = ({name: item.eventName,type: EntityTypes.EVENTS,properties: quickFilterToPropertyFilters(item),+ negation,})setChangingEvent(false)return}const entityType = taxonomicFilterGroupTypeToEntityType(taxonomicGroup.type)if (entityType) {- onChange({ id: value, name: item?.name ?? String(value), type: entityType, properties: [] })+ onChange({ id: value, name: item?.name ?? String(value), type: entityType, properties: [], negation })}setChangingEvent(false)}@@ -157,6 +198,7 @@ const Value = ({/>) : (<>+ {negationSelect}<div className="px-2 py-1"><LemonButton size="xsmall" type="secondary" onClick={() => setChangingEvent(true)}>Change event@@ -190,6 +232,8 @@ const Value = ({operatorAllowlist={operatorAllowlist}endpointFilters={endpointFilters}/>+ ) : isAction && negationSelect ? (+ <div>{negationSelect}</div>) : null}>@@ -198,6 +242,7 @@ const Value = ({onClose={onRemove}filter={filter}className={className}+ clickable={isAction && !!negationSelect}/></Popover>)diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 872220f80ba6..f629b787ef6d 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -471,6 +471,7 @@ export const FEATURE_FLAGS = {REPLAY_COLLAPSE_INSPECTOR_ITEMS: 'replay-collapse-inspector-items', // owner: @fasyy612 #team-replayREPLAY_EXPERIMENT_CONTEXT: 'replay-experiment-context', // owner: @mp-hog #team-experimentsREPLAY_FILTERS_REDESIGN: 'replay-filters-redesign', // owner: @ksvat #team-replay+ REPLAY_NEGATIVE_EVENT_FILTERS: 'replay-negative-event-filters', // owner: @arnohillen #team-replayREPLAY_PLAYLIST_RELEVANCE_SORT_EXPERIMENT: 'replay-playlist-relevance-sort-experiment', // owner: @arnohillen #team-replay multivariate=control,testREPLAY_PLAYLIST_SURFACING_SCORE: 'replay-playlist-surfacing-score', // owner: #team-replayREPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replaydiff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.tsindex 4100c0af147a..0e4ed0bbf8ef 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts@@ -70,6 +70,7 @@ export interface actionFilterGroupLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -92,6 +93,7 @@ export interface actionFilterGroupLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -115,6 +117,7 @@ export interface actionFilterGroupLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -138,6 +141,7 @@ export interface actionFilterGroupLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefineddiff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.tsindex ee32e1008f0a..b4fe8d74866f 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts@@ -220,6 +220,7 @@ export interface entityFilterLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -242,6 +243,7 @@ export interface entityFilterLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -265,6 +267,7 @@ export interface entityFilterLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefined@@ -288,6 +291,7 @@ export interface entityFilterLogicActions {math_property?: string | null | undefinedmath_property_type?: TaxonomicFilterGroupType | null | undefinedname?: string | null | undefined+ negation?: boolean | undefinednestedFilters?: EntityFilter[] | null | undefinedoperator?: FilterLogicalOperator | null | undefinedoptionalInFunnel?: boolean | undefineddiff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsxindex 7ad79714c192..8aee7d53b61d 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx@@ -381,6 +381,7 @@ const RecordingsUniversalFilterGroup = ({const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)const [allowInitiallyOpen, setAllowInitiallyOpen] = useState(false)const [isPopoverVisible, setIsPopoverVisible] = useState(false)+ const allowEntityNegation = useFeatureFlag('REPLAY_NEGATIVE_EVENT_FILTERS')useOnMountEffect(() => setAllowInitiallyOpen(true))return (@@ -430,6 +431,7 @@ const RecordingsUniversalFilterGroup = ({onChange={(value) => replaceGroupValue(index, value)}initiallyOpen={allowInitiallyOpen}metadataSource={{ kind: NodeKind.RecordingsQuery }}+ allowEntityNegation={allowEntityNegation}operatorAllowlist={isCommentTextFilter(filterOrGroup)? [PropertyOperator.IsSet, PropertyOperator.Exact, PropertyOperator.IContains]diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.tsindex e10ecb516411..1263bd9942b6 100644--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts@@ -29,6 +29,8 @@ function innerValues(query: RecordingsQuery | null | undefined): any[] {const EVENT = { id: '$pageview', type: 'events' }const ACTION = { id: '5', type: 'actions' }+const NEGATED_EVENT = { id: 'purchase', type: 'events', negation: true }+const NEGATED_ACTION = { id: '7', type: 'actions', negation: true }const PERSON_PROP: AnyPropertyFilter = {type: PropertyFilterType.Person,key: 'email',@@ -79,6 +81,8 @@ describe('recordingsQueryToUniversalFilters', () => {it.each<[string, Partial<RecordingsQuery>, any[]]>([['events', { events: [EVENT] }, [EVENT]],['actions', { actions: [ACTION] }, [ACTION]],+ ['negated events', { events: [NEGATED_EVENT] }, [NEGATED_EVENT]],+ ['negated actions', { actions: [NEGATED_ACTION] }, [NEGATED_ACTION]],['properties', { properties: [PERSON_PROP] }, [PERSON_PROP]],['console_log_filters', { console_log_filters: [CONSOLE_LOG] }, [CONSOLE_LOG]],['comment_text', { comment_text: COMMENT_TEXT }, [COMMENT_TEXT]],@@ -188,6 +192,13 @@ describe('convertUniversalFiltersToRecordingsQuery ∘ recordingsQueryToUniversa})})+ it('preserves entity negation on events and actions', () => {+ const query = rq({ events: [EVENT, NEGATED_EVENT], actions: [NEGATED_ACTION] })+ const back = roundTrip(query)+ expect(back.events).toEqual([EVENT, NEGATED_EVENT])+ expect(back.actions).toEqual([NEGATED_ACTION])+ })+it('preserves the classifier events filter that was previously hidden', () => {const events = [{ id: 'taxonomic filter add filter clicked', type: 'events' }]expect(roundTrip(rq({ events })).events).toEqual(events)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex ff4e7588b3ee..d422c2b1bacb 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1617,6 +1617,8 @@ export interface ActionFilter extends EntityFilter {days?: string[] // TODO: why was this added here?operator?: FilterLogicalOperator | nullnestedFilters?: EntityFilter[] | null+ /** Replay-only. When true, matches sessions that do NOT contain any event matching this entity */+ negation?: boolean}export const isGroupFilter = (filter: EntityFilter): filter is ActionFilter => filter.type === EntityTypes.GROUPSdiff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 6911b478cb58..deaa25886c87 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -229,6 +229,15 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):),)+ # After the results are in, check whether the exclusion blocklist hit its row cap,+ # because past the cap the query silently under-excludes. No-op without negated entities.+ 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 = Noneif isinstance(self._paginator, HogQLCursorPaginator):diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.pyindex d0177582981c..93b4305f8110 100644--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py@@ -1,8 +1,9 @@from collections.abc import Iterablefrom datetime import datetime, timedelta-from typing import Optional, cast+from typing import Any, Optional, castimport posthoganalytics+from prometheus_client import Counterfrom posthog.schema import (ActionsNode,@@ -36,6 +37,15 @@ from posthog.session_recordings.queries.utils import ()from posthog.types import AnyPropertyFilter+# Cap on the negative blocklist subquery, kept for memory safety. Sessions past the cap+# are silently not excluded, so hitting it is observed by check_negative_blocklist_truncation.+NEGATIVE_BLOCKLIST_LIMIT = 1_000_000++REPLAY_NEGATIVE_BLOCKLIST_TRUNCATED_COUNTER = Counter(+ "replay_negative_blocklist_truncated",+ "A replay exclusion blocklist hit its row cap, so some sessions were not excluded from the results",+)+# Person properties eligible for hybrid query optimization# These are high-selectivity identity properties where the three-stage query provides valueHYBRID_QUERY_ELIGIBLE_PROPERTIES = {@@ -563,9 +573,15 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):right=q,))+ # Exclusion-only filter sets (every entity negated) produce no positive predicates.+ # Wrapping an empty list prints as `and()`, which ClickHouse rejects, so match nothing:+ # there are no positive events to highlight in the player.+ where_expr: ast.Expr = (+ self.wrapped_with_query_operand(exprs=select_exprs) if select_exprs else ast.Constant(value=False)+ )return self._select_from_events(select_expr=[ast.Field(chain=["uuid"]), ast.Call(name="any", args=[ast.Field(chain=["timestamp"])])],- where_expr=self.wrapped_with_query_operand(exprs=select_exprs),+ where_expr=where_expr,# when matching we want to select flag lists of event UUIds so we group by session_id, and then uuidgroup_by=[_event_session_id_field(), ast.Field(chain=["uuid"])],limit_expr=ast.Constant(value=10000),@@ -674,21 +690,42 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):exprs = [countif_zero(p) for p in self._collect_negative_properties()]return self.wrapped_with_query_operand(exprs=exprs) if exprs else ast.Constant(value=True)+ @staticmethod+ def _is_negated_entity(raw_entity: dict[str, Any]) -> bool:+ return bool(raw_entity.get("negation"))+@propertydef action_entities(self):# TODO what do we send to the API instead to avoid needing to do this- return [legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable) for e in self._query.actions or []]+ return [+ legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)+ for e in self._query.actions or []+ if not self._is_negated_entity(e)+ ]@propertydef event_entities(self):# TODO what do we send to the API instead to avoid needing to do this# TODO is this overkill since it feels like we only need a few things off the entity- return [legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable) for e in self._query.events or []]+ return [+ legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)+ for e in self._query.events or []+ if not self._is_negated_entity(e)+ ]@propertydef entities(self):return self.action_entities + self.event_entities+ @property+ def negated_entities(self) -> list[EventsNode | ActionsNode | DataWarehouseNode | str]:+ # the legacy Entity class drops unknown keys, so negation is read off the raw dicts+ return [+ legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)+ for e in (self._query.actions or []) + (self._query.events or [])+ if self._is_negated_entity(e)+ ]+@propertydef event_properties(self):return [g for g in (self._query.properties or []) if is_event_property(g)]@@ -731,7 +768,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):def _negative_blocklist_query(self) -> ast.SelectQuery | None:"""Returns session IDs that should be EXCLUDED because they contain events- matching at least one inverted negative condition.+ matching at least one inverted negative condition or one negated entity.This is a blocklist approach: instead of scanning ALL events and keeping sessionswhere no events match (allowlist), we find the small set of sessions that DO match@@ -740,32 +777,69 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):The blocklist is much smaller than the allowlist for typical negative filters(e.g. "host is not internal IP" → blocklist contains only internal IP sessions).This avoids hitting the LIMIT on high-traffic teams with millions of event-sessions.++ Negated entities ("did not perform X") are global constraints and apply under both+ operands. Negative property filters stay AND-only because inverting them under OR+ would change existing semantics."""- if self._query.operand == "OR":- return None+ # a negated entity's predicate is already the positive form: sessions performing it get blocked+ blocklist_exprs: list[ast.Expr] = self._event_predicates(self.negated_entities, self._team)- negative_props = self._collect_negative_properties()- if not negative_props:- return None+ if self._query.operand != "OR":+ for prop in self._collect_negative_properties():+ operator = cast(PropertyOperator, prop.operator) # type: ignore[union-attr]+ inverted = prop.model_copy(update={"operator": INVERSE_OPERATOR_FOR[operator]})+ blocklist_exprs.append(property_to_expr(inverted, team=self._team, scope="event"))- # Build inverted (positive) expressions for each negative property- inverted_exprs: list[ast.Expr] = []- for prop in negative_props:- operator = cast(PropertyOperator, prop.operator) # type: ignore[union-attr]- inverted = prop.model_copy(update={"operator": INVERSE_OPERATOR_FOR[operator]})- inverted_exprs.append(property_to_expr(inverted, team=self._team, scope="event"))+ if not blocklist_exprs:+ return None# Any event matching any positive condition → session goes in blocklist- where_expr = ast.Or(exprs=inverted_exprs) if len(inverted_exprs) > 1 else inverted_exprs[0]+ where_expr = ast.Or(exprs=blocklist_exprs) if len(blocklist_exprs) > 1 else blocklist_exprs[0]return ast.SelectQuery(select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],select_from=self._events_join(sample=False),where=self._where_predicates(where_expr, apply_timestamp_floor=False),group_by=[_event_session_id_field()],- limit=ast.Constant(value=1000000),+ # Negating a very common event (e.g. $pageview) can push the blocklist past this cap on+ # high-traffic teams, silently under-excluding sessions beyond it. Typical negatives (rare+ # events, property filters) stay well under it, so the bound is kept for memory safety.+ limit=ast.Constant(value=NEGATIVE_BLOCKLIST_LIMIT),)+ def check_negative_blocklist_truncation(self) -> None:+ """The blocklist is embedded as a NOT GlobalIn subquery, so the main query never sees+ its row count. Probe it separately and record when it hit its cap, because past the cap+ sessions that DID perform the excluded event come back in the results. Only runs when+ negated entities are present, to bound the extra query cost to the exclusion feature."""+ if not self.negated_entities:+ return+ blocklist = self._negative_blocklist_query()+ if blocklist is None:+ return+ try:+ with tracer.start_as_current_span(+ "ReplayFiltersEventsSubQuery.check_negative_blocklist_truncation"+ ) as span:+ response = execute_hogql_query(+ query=ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=blocklist),+ ),+ team=self._team,+ query_type="ReplayNegativeBlocklistTruncationProbe",+ modifiers=self._hogql_query_modifiers,+ )+ blocklist_size = response.results[0][0] if response.results else 0+ truncated = blocklist_size >= NEGATIVE_BLOCKLIST_LIMIT+ span.set_attribute("replay.negative_blocklist.size", blocklist_size)+ span.set_attribute("replay.negative_blocklist.truncated", truncated)+ if truncated:+ REPLAY_NEGATIVE_BLOCKLIST_TRUNCATED_COUNTER.inc()+ except Exception as e:+ posthoganalytics.capture_exception(e, properties={"replay_feature": "negative_blocklist_truncation_probe"})+@staticmethod@tracer.start_as_current_span("ReplayFiltersEventsSubQuery.with_team_events_added")def with_team_events_added(p: AnyPropertyFilter, team: Team) -> tuple[list[str], 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.pyindex c1889a11063a..3ddea01f5eff 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@@ -40,6 +40,7 @@ from posthog.session_recordings.queries.session_recording_list_from_query importSessionRecordingListFromQuery,SessionRecordingQueryResult,)+from posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQueryfrom posthog.session_recordings.queries.test.listing_recordings.test_utils import (assert_query_matches_session_ids,create_event,@@ -792,6 +793,335 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):[],)+ @parameterized.expand([("AND",), ("OR",)])+ def test_negated_event_filter_excludes_sessions_containing_event(self, operand: str) -> None:+ user = "test_negated_event_filter-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})++ session_with_purchase = f"with-purchase-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_with_purchase,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_with_purchase, "$window_id": "1"},+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ event_name="purchase",+ properties={"$session_id": session_with_purchase, "$window_id": "1"},+ )++ session_without_purchase = f"without-purchase-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_without_purchase,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_without_purchase, "$window_id": "1"},+ )++ self._assert_query_matches_session_ids(+ {+ "operand": operand,+ "events": [+ {"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"},+ {"id": "purchase", "type": "events", "order": 1, "name": "purchase", "negation": True},+ ],+ },+ [session_without_purchase],+ )++ self._assert_query_matches_session_ids(+ {+ "operand": operand,+ "events": [+ {"id": "purchase", "type": "events", "order": 0, "name": "purchase", "negation": True},+ ],+ },+ [session_without_purchase],+ )++ def test_negated_event_filter_respects_entity_property_filters(self) -> None:+ user = "test_negated_event_props-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})++ session_success = f"success-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_success,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={+ "$session_id": session_success,+ "$window_id": "1",+ "$current_url": "https://app.io/checkout/success",+ },+ )++ session_other = f"other-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_other,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={+ "$session_id": session_other,+ "$window_id": "1",+ "$current_url": "https://app.io/pricing",+ },+ )++ self._assert_query_matches_session_ids(+ {+ "events": [+ {+ "id": "$pageview",+ "type": "events",+ "order": 0,+ "name": "$pageview",+ "negation": True,+ "properties": [+ {+ "key": "$current_url",+ "value": "/checkout/success",+ "operator": "icontains",+ "type": "event",+ }+ ],+ }+ ],+ },+ [session_other],+ )++ def test_negated_action_filter_excludes_sessions_containing_action(self) -> None:+ user = "test_negated_action-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ action = self.create_action("custom-event")++ session_with_action = f"with-action-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_with_action,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ event_name="custom-event",+ properties={"$session_id": session_with_action, "$window_id": "1"},+ )++ session_without_action = f"without-action-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_without_action,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_without_action, "$window_id": "1"},+ )++ self._assert_query_matches_session_ids(+ {+ "actions": [+ {"id": action.id, "type": "actions", "order": 0, "name": action.name, "negation": True},+ ],+ },+ [session_without_action],+ )++ def test_negated_event_filter_does_not_affect_matching_events(self) -> None:+ user = "test_negated_matching-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ session_id = f"matching-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_id,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ pageview_uuid = create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_id, "$window_id": "1"},+ )++ query = RecordingsQuery.model_validate(+ {+ "session_ids": [session_id],+ "events": [+ {"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"},+ {"id": "purchase", "type": "events", "order": 1, "name": "purchase", "negation": True},+ ],+ }+ )+ result = ReplayFiltersEventsSubQuery(team=self.team, query=query).get_event_ids_for_session()+ assert [str(row[0]) for row in result.results] == [pageview_uuid]++ def test_exclusion_only_filter_returns_no_matching_events(self) -> None:+ # with only negated entities there are no positive predicates, so the matching-events+ # query must execute and return empty rather than erroring on an empty operand wrapper+ user = "test_exclusion_only_matching-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ session_id = f"exclusion-only-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user,+ session_id=session_id,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.id,+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_id, "$window_id": "1"},+ )++ query = RecordingsQuery.model_validate(+ {+ "session_ids": [session_id],+ "events": [+ {"id": "purchase", "type": "events", "order": 0, "name": "purchase", "negation": True},+ ],+ }+ )+ result = ReplayFiltersEventsSubQuery(team=self.team, query=query).get_event_ids_for_session()+ assert result.results == []++ def test_multiple_negated_event_filters_exclude_sessions_matching_any(self) -> None:+ user = "test_multiple_negated-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})++ session_purchase = f"purchase-{str(uuid4())}"+ session_signup = f"signup-{str(uuid4())}"+ session_neither = f"neither-{str(uuid4())}"+ for session_id, extra_event in [+ (session_purchase, "purchase"),+ (session_signup, "signup"),+ (session_neither, None),+ ]:+ produce_replay_summary(+ distinct_id=user, session_id=session_id, first_timestamp=self.an_hour_ago, team_id=self.team.id+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_id, "$window_id": "1"},+ )+ if extra_event:+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ event_name=extra_event,+ properties={"$session_id": session_id, "$window_id": "1"},+ )++ # The blocklist unions both negated entities, so matching either one excludes the session.+ self._assert_query_matches_session_ids(+ {+ "events": [+ {"id": "purchase", "type": "events", "order": 0, "name": "purchase", "negation": True},+ {"id": "signup", "type": "events", "order": 1, "name": "signup", "negation": True},+ ],+ },+ [session_neither],+ )++ def test_negated_entity_and_negative_property_share_one_blocklist(self) -> None:+ user = "test_negated_combined-user"+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})++ session_purchase = f"purchase-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user, session_id=session_purchase, first_timestamp=self.an_hour_ago, team_id=self.team.id+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_purchase, "$window_id": "1", "$current_url": "https://app.io/home"},+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ event_name="purchase",+ properties={"$session_id": session_purchase, "$window_id": "1"},+ )++ session_internal = f"internal-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user, session_id=session_internal, first_timestamp=self.an_hour_ago, team_id=self.team.id+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={+ "$session_id": session_internal,+ "$window_id": "1",+ "$current_url": "https://app.io/internal/dashboard",+ },+ )++ session_clean = f"clean-{str(uuid4())}"+ produce_replay_summary(+ distinct_id=user, session_id=session_clean, first_timestamp=self.an_hour_ago, team_id=self.team.id+ )+ create_event(+ team=self.team,+ distinct_id=user,+ timestamp=self.an_hour_ago,+ properties={"$session_id": session_clean, "$window_id": "1", "$current_url": "https://app.io/home"},+ )++ # A negated entity and a negative event property both feed the single AND blocklist. A session+ # matching either (did purchase, or visited /internal) is excluded.+ self._assert_query_matches_session_ids(+ {+ "events": [+ {"id": "purchase", "type": "events", "order": 0, "name": "purchase", "negation": True},+ ],+ "properties": [+ {"key": "$current_url", "value": "/internal", "operator": "not_icontains", "type": "event"},+ ],+ },+ [session_clean],+ )+@snapshot_clickhouse_queriesdef test_event_filter_has_ttl_applied_too(self):user = "test_event_filter_has_ttl_applied_too-user"diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsxindex 3d18ba5a7136..0511c11476bb 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx@@ -10,6 +10,7 @@ import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'import { FEATURE_FLAGS } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonLabel } from 'lib/lemon-ui/LemonLabel'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'@@ -69,6 +70,7 @@ export function groupHasNoFilters(group: UniversalFiltersGroup): boolean {function ScannerFilterGroup(): JSX.Element {const { filterGroup } = useValues(universalFiltersLogic)const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)+ const allowEntityNegation = useFeatureFlag('REPLAY_NEGATIVE_EVENT_FILTERS')return (<div className="flex flex-wrap items-center gap-2">@@ -84,6 +86,7 @@ function ScannerFilterGroup(): JSX.Element {filter={filterOrGroup}onRemove={() => removeGroupValue(index)}onChange={(value) => replaceGroupValue(index, value)}+ allowEntityNegation={allowEntityNegation}/>))}