Skip to content

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

fix(surveys): match notification filters when testing with last response (#78000)

Daniel Marchuk37fea8362ea0
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
index 615ee645ac67..d79a267c5f51 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
@@ -56,7 +56,7 @@ function TestResultPanel({
: result?.status === 'success'
? 'Test notification sent.'
: result?.status === 'skipped'
- ? 'Test was skipped — the event did not match the notification filters.'
+ ? "Test skipped. The test event didn't match this notification's filters. Adjust the filters and try again."
: 'Test failed.'
return (
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
index 81d1bafe828d..e55da480a27c 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
@@ -1,13 +1,23 @@
import { NEW_SURVEY } from 'scenes/surveys/constants'
import { NodeKind } from '~/queries/schema/schema-general'
-import { PropertyFilterType, PropertyOperator, SurveyEventProperties, SurveyQuestionType } from '~/types'
+import {
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ SurveyEventName,
+ SurveyEventProperties,
+ SurveyQuestionType,
+} from '~/types'
import {
+ alignGlobalsWithNotificationFilter,
buildLastSurveyResponseQuery,
getDefaultSurveyMessage,
remapSurveyResponseProperties,
} from './surveyNotificationModalLogic'
+import { buildSurveyExampleInvocationGlobals } from './utils'
describe('surveyNotificationModalLogic', () => {
it('includes survey status text in the default notification message', () => {
@@ -64,17 +74,18 @@ describe('surveyNotificationModalLogic', () => {
})
it.each([NEW_SURVEY.id, ''])('returns no query when building a last-response lookup for survey id "%s"', (id) => {
- expect(buildLastSurveyResponseQuery(id)).toBeNull()
+ expect(buildLastSurveyResponseQuery(id, null)).toBeNull()
})
- it('builds a last-response events query scoped to the survey, matching sent or dismissed', () => {
- const query = buildLastSurveyResponseQuery('survey-abc')
+ it('builds a last-response events query scoped to the survey when the notification has no filters', () => {
+ const query = buildLastSurveyResponseQuery('survey-abc', null)
expect(query).toMatchObject({
kind: NodeKind.EventsQuery,
select: ['*', 'person'],
limit: 1,
after: '-90d',
orderBy: ['timestamp DESC'],
+ events: [SurveyEventName.SENT, SurveyEventName.DISMISSED],
})
expect(query?.fixedProperties).toEqual([
{
@@ -83,13 +94,116 @@ describe('surveyNotificationModalLogic', () => {
value: 'survey-abc',
operator: PropertyOperator.Exact,
},
+ ])
+ })
+
+ it('requires the last response to match one of the notification event filters', () => {
+ const completedFilter: EventPropertyFilter = {
+ key: SurveyEventProperties.SURVEY_COMPLETED,
+ type: PropertyFilterType.Event,
+ value: true,
+ operator: PropertyOperator.Exact,
+ }
+ const ratingFilter: EventPropertyFilter = {
+ key: '$survey_response_question-1',
+ type: PropertyFilterType.Event,
+ value: 8,
+ operator: PropertyOperator.GreaterThanOrEqual,
+ }
+ const globalFilter: EventPropertyFilter = {
+ key: '$browser',
+ type: PropertyFilterType.Event,
+ value: 'Chrome',
+ operator: PropertyOperator.Exact,
+ }
+
+ const query = buildLastSurveyResponseQuery('survey-abc', {
+ events: [
+ { id: SurveyEventName.SENT, type: 'events', properties: [completedFilter, ratingFilter] },
+ { id: SurveyEventName.DISMISSED, type: 'events', properties: [] },
+ ],
+ properties: [globalFilter],
+ filter_test_accounts: true,
+ })
+
+ expect(query?.event).toBeUndefined()
+ expect(query?.events).toBeUndefined()
+ expect(query?.filterTestAccounts).toBe(true)
+ expect(query?.fixedProperties).toEqual([
{
- type: PropertyFilterType.HogQL,
- key: "event IN ('survey sent', 'survey dismissed')",
+ key: SurveyEventProperties.SURVEY_ID,
+ type: PropertyFilterType.Event,
+ value: 'survey-abc',
+ operator: PropertyOperator.Exact,
+ },
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.Or,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ completedFilter,
+ ratingFilter,
+ { type: PropertyFilterType.HogQL, key: "event = 'survey sent'" },
+ ],
+ },
+ {
+ type: FilterLogicalOperator.And,
+ values: [{ type: PropertyFilterType.HogQL, key: "event = 'survey dismissed'" }],
+ },
+ ],
+ },
+ { type: FilterLogicalOperator.And, values: [globalFilter] },
+ ],
},
])
})
+ it.each([
+ [
+ 'copies an exact value the sample is missing',
+ { key: '$browser', operator: PropertyOperator.Exact, value: 'Chrome' },
+ 'Chrome',
+ ],
+ [
+ 'copies the first accepted value of an is-any-of filter',
+ { key: '$survey_response_q1', operator: PropertyOperator.Exact, value: ['Other', 'Bug'] },
+ 'Other',
+ ],
+ [
+ 'leaves the sample alone for a negated filter',
+ { key: '$survey_response_q1', operator: PropertyOperator.IsNot, value: 'Other' },
+ // The example globals answer an open question with its own text.
+ 'What could be better?',
+ ],
+ ])('aligning sample globals with the notification filter %s', (_name, property, expected) => {
+ const globals = buildSurveyExampleInvocationGlobals({
+ survey: {
+ id: 'survey-abc',
+ name: 'Survey',
+ questions: [{ id: 'q1', question: 'What could be better?', type: SurveyQuestionType.Open }],
+ },
+ projectId: 1,
+ projectName: 'Project',
+ projectUrl: 'https://example.com/project/1',
+ })
+
+ const aligned = alignGlobalsWithNotificationFilter(globals, {
+ events: [
+ {
+ id: SurveyEventName.SENT,
+ type: 'events',
+ properties: [{ ...property, type: PropertyFilterType.Event } as EventPropertyFilter],
+ },
+ ],
+ })
+
+ expect(aligned.event.properties[property.key]).toEqual(expected)
+ })
+
it('removes copied survey response properties that do not have a target question', () => {
const copiedInputs = {
text: {
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
index 940e54a3b97d..dabc9bdbf717 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
@@ -31,16 +31,22 @@ import { urls } from 'scenes/urls'
import { performQuery } from '~/queries/query'
import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
+import { hogql } from '~/queries/utils'
import {
+ AnyPropertyFilter,
+ CyclotronJobFiltersType,
CyclotronJobInvocationGlobals,
CyclotronJobTestInvocationResult,
EventPropertyFilter,
EventType,
+ FilterLogicalOperator,
HogFunctionTemplateType,
HogFunctionType,
IntegrationType,
PersonType,
PropertyFilterType,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
PropertyOperator,
Survey,
SurveyEventName,
@@ -266,28 +272,77 @@ function buildTemplateGlobals(survey: SurveyNotificationContext): CyclotronJobIn
})
}
-export function buildLastSurveyResponseQuery(surveyId: string): EventsQuery | null {
+/**
+ * The events the notification would fire on, as an OR of one AND-group per event, which is the
+ * same shape the full destination editor uses to list matching events (`matchingFilters` in
+ * `hogFunctionConfigurationLogic`).
+ */
+function buildNotificationMatchGroup(filters: CyclotronJobFiltersType | null): PropertyGroupFilter | null {
+ const events = filters?.events ?? []
+ if (events.length === 0) {
+ return null
+ }
+
+ const eventGroups: PropertyGroupFilterValue = {
+ type: FilterLogicalOperator.Or,
+ values: events.map((event) => ({
+ type: FilterLogicalOperator.And,
+ values: [
+ ...((event.properties ?? []) as AnyPropertyFilter[]),
+ { type: PropertyFilterType.HogQL, key: hogql`event = ${event.id}` },
+ ],
+ })),
+ }
+ const globalProperties = (filters?.properties ?? []) as AnyPropertyFilter[]
+
+ return {
+ type: FilterLogicalOperator.And,
+ values: [
+ eventGroups,
+ ...(globalProperties.length > 0
+ ? [{ type: FilterLogicalOperator.And, values: globalProperties } as PropertyGroupFilterValue]
+ : []),
+ ],
+ }
+}
+
+/**
+ * The newest response the notification would actually have fired on. Selecting on anything less
+ * hands the test an event the notification rejects (a partial `survey sent`, a rating below the
+ * configured threshold), and the test is skipped with no way for the user to tell why.
+ *
+ * Only the top-level filters are read. `buildHogFunctionInvocations` evaluates those for every
+ * function, and additionally requires a mapping to match when the function has mappings, so an
+ * event that fails them is rejected outright. Survey notifications carry no mappings, so this
+ * is exact for anything this modal creates.
+ */
+export function buildLastSurveyResponseQuery(
+ surveyId: string,
+ filters: CyclotronJobFiltersType | null
+): EventsQuery | null {
if (!surveyId || surveyId === NEW_SURVEY.id) {
return null
}
+
+ // Saved filters already scope by survey, but a hand-edited one may not, and pulling another
+ // survey's response into this survey's test would be worse than finding nothing.
+ const surveyIdProperty: EventPropertyFilter = {
+ key: SurveyEventProperties.SURVEY_ID,
+ type: PropertyFilterType.Event,
+ value: surveyId,
+ operator: PropertyOperator.Exact,
+ }
+ const matchGroup = buildNotificationMatchGroup(filters)
+
return {
kind: NodeKind.EventsQuery,
select: ['*', 'person'],
- fixedProperties: [
- {
- key: SurveyEventProperties.SURVEY_ID,
- type: PropertyFilterType.Event,
- value: surveyId,
- operator: PropertyOperator.Exact,
- },
- {
- type: PropertyFilterType.HogQL,
- key: `event IN ('${SurveyEventName.SENT}', '${SurveyEventName.DISMISSED}')`,
- },
- ],
after: '-90d',
orderBy: ['timestamp DESC'],
limit: 1,
+ filterTestAccounts: filters?.filter_test_accounts,
+ events: matchGroup ? undefined : [SurveyEventName.SENT, SurveyEventName.DISMISSED],
+ fixedProperties: matchGroup ? [surveyIdProperty, matchGroup] : [surveyIdProperty],
modifiers: {
personsOnEventsMode: 'person_id_no_override_properties_on_events',
},
@@ -300,24 +355,51 @@ type LastSurveyResponseResult =
| { status: 'failed' }
/**
- * Aligns sample globals with the saved notification's first event filter so the test
- * passes the compiled filter bytecode. Without this, a tiny mismatch (e.g. a survey id
+ * Operators where copying the filter's own value into the sample event satisfies the filter.
+ * An allowlist rather than a list of negations to skip, so an operator nobody thought about
+ * leaves the sample alone instead of being handed a value that makes the filter reject it.
+ */
+const SAMPLE_SATISFIABLE_OPERATORS = new Set<PropertyOperator>([
+ PropertyOperator.Exact,
+ PropertyOperator.IContains,
+ PropertyOperator.GreaterThanOrEqual,
+ PropertyOperator.LessThanOrEqual,
+ PropertyOperator.IsSet,
+])
+
+/**
+ * Aligns sample globals with the first event filter of the configuration being tested so the
+ * test passes the compiled filter bytecode. Without this, a tiny mismatch (e.g. a survey id
* that drifted from `values.survey.id` due to copying or migration) skips the test.
*/
-function alignGlobalsWithNotificationFilter(
+export function alignGlobalsWithNotificationFilter(
globals: CyclotronJobInvocationGlobals,
- notification: HogFunctionType | null
+ filters: CyclotronJobFiltersType | null
): CyclotronJobInvocationGlobals {
- const effectiveFilter = notification?.mappings?.[0]?.filters ?? notification?.filters ?? null
- const firstEvent = effectiveFilter?.events?.[0]
+ const firstEvent = filters?.events?.[0]
if (!firstEvent) {
return globals
}
const mergedProperties = { ...globals.event.properties }
for (const prop of firstEvent.properties ?? []) {
- if ('key' in prop && prop.key && 'value' in prop && prop.value !== undefined) {
- mergedProperties[prop.key] = prop.value
+ if (!('key' in prop) || !prop.key || !('value' in prop) || prop.value === undefined) {
+ continue
+ }
+ // A property filter with no operator is an exact match, both here and in the backend.
+ const operator = prop.operator ?? PropertyOperator.Exact
+ if (!SAMPLE_SATISFIABLE_OPERATORS.has(operator)) {
+ continue
+ }
+ // `is set` carries a sentinel rather than a real value, so only fill in a missing key.
+ if (operator === PropertyOperator.IsSet && mergedProperties[prop.key] !== undefined) {
+ continue
}
+ // An `is any of` filter stores every accepted value; one of them is enough for the sample.
+ const value = Array.isArray(prop.value) ? prop.value[0] : prop.value
+ if (value === undefined) {
+ continue
+ }
+ mergedProperties[prop.key] = value
}
return {
...globals,
@@ -873,7 +955,6 @@ export interface surveyNotificationModalLogicValues {
isNotificationFormSubmitting: boolean
isNotificationFormValid: boolean
isOpen: boolean
- lastResponseEventQuery: EventsQuery | null
notificationForm: SurveyNotificationForm
notificationFormAllErrors: Record<string, any>
notificationFormChanged: boolean
@@ -1122,7 +1203,6 @@ export interface surveyNotificationModalLogicMeta {
notificationForm: SurveyNotificationForm
) => IntegrationType | null
templateGlobals: (survey: NewSurvey | Survey) => CyclotronJobInvocationGlobals
- lastResponseEventQuery: (survey: NewSurvey | Survey) => EventsQuery | null
submitDisabledReason: (
survey: NewSurvey | Survey,
notificationFormErrors: DeepPartialMap<SurveyNotificationForm, ValidationErrorType>,
@@ -1233,28 +1313,36 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
copiedNotification: values.copiedNotification,
})
+ // Filter against the configuration being tested, not the saved notification,
+ // so unsaved filter edits in the modal are reflected in the test.
+ const filters = configuration.filters ?? null
+
let globals: CyclotronJobInvocationGlobals = values.templateGlobals
let usingSample = source === 'sample'
if (source === 'last_response') {
- const lookup = await fetchLastSurveyResponseGlobals(values.lastResponseEventQuery)
+ const lookup = await fetchLastSurveyResponseGlobals(
+ buildLastSurveyResponseQuery(values.survey.id, filters)
+ )
if (lookup.status === 'ok') {
globals = lookup.globals
} else if (lookup.status === 'failed') {
usingSample = true
lemonToast.warning(
- 'Could not fetch the last response — sent the test with sample data instead.'
+ "Couldn't load the last response. Sent the test with sample data instead."
)
} else {
usingSample = true
- lemonToast.info('No survey responses yet — sent the test with sample data instead.')
+ lemonToast.info(
+ 'No response in the last 90 days matches these filters. Sent the test with sample data instead.'
+ )
}
}
- // Align sample globals with the saved filter's expected values so the test
+ // Align sample globals with the filter's expected values so the test
// isn't skipped by a $survey_id or completion-flag mismatch. Applies to an
// explicit sample-data test and to a last-response test that fell back to it.
if (usingSample) {
- globals = alignGlobalsWithNotificationFilter(globals, values.editingNotification)
+ globals = alignGlobalsWithNotificationFilter(globals, filters)
}
const id = values.editingNotification?.id ?? 'new'
@@ -1308,10 +1396,6 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
null,
],
templateGlobals: [(s) => [s.survey], (survey: SurveyNotificationContext) => buildTemplateGlobals(survey)],
- lastResponseEventQuery: [
- (s) => [s.survey],
- (survey: SurveyNotificationContext): EventsQuery | null => buildLastSurveyResponseQuery(survey.id),
- ],
submitDisabledReason: [
(s) => [
s.survey,