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): notify on completed responses when partial responses are off (#81268)

Daniel Marchukde04742395f5
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
index e55da480a27c..4801123734d0 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
@@ -4,6 +4,7 @@ import { NodeKind } from '~/queries/schema/schema-general'
import {
EventPropertyFilter,
FilterLogicalOperator,
+ HogFunctionType,
PropertyFilterType,
PropertyOperator,
SurveyEventName,
@@ -15,9 +16,10 @@ import {
alignGlobalsWithNotificationFilter,
buildLastSurveyResponseQuery,
getDefaultSurveyMessage,
+ mergeResponseFiltersIntoExistingFilters,
remapSurveyResponseProperties,
} from './surveyNotificationModalLogic'
-import { buildSurveyExampleInvocationGlobals } from './utils'
+import { buildSurveyExampleInvocationGlobals, getSurveyNotificationFilters } from './utils'
describe('surveyNotificationModalLogic', () => {
it('includes survey status text in the default notification message', () => {
@@ -235,4 +237,82 @@ describe('surveyNotificationModalLogic', () => {
},
})
})
+
+ // The full Hog editor can put a restriction on either sent branch, so both indexes have to
+ // survive the rebuild. Properties are AND'd, so losing one would widen delivery.
+ it.each([0, 1])('keeps a restriction added outside the modal on sent branch %s', (branchIndex) => {
+ const customRestriction: EventPropertyFilter = {
+ key: '$browser',
+ type: PropertyFilterType.Event,
+ value: 'Chrome',
+ operator: PropertyOperator.Exact,
+ }
+ const saved = getSurveyNotificationFilters('survey-abc', false)
+ const branch = saved.events![branchIndex]
+ branch.properties = [...(branch.properties ?? []), customRestriction]
+
+ const merged = mergeResponseFiltersIntoExistingFilters(
+ saved,
+ getSurveyNotificationFilters('survey-abc', false),
+ []
+ )
+
+ const sentBranches = merged?.events?.filter((event) => event.id === SurveyEventName.SENT)
+ expect(sentBranches).toHaveLength(2)
+ for (const sentBranch of sentBranches ?? []) {
+ expect(sentBranch.properties).toContainEqual(customRestriction)
+ }
+ })
+
+ it('does not accumulate copies of a custom restriction across repeated saves', () => {
+ const customRestriction: EventPropertyFilter = {
+ key: '$browser',
+ type: PropertyFilterType.Event,
+ value: 'Chrome',
+ operator: PropertyOperator.Exact,
+ }
+ const saved = getSurveyNotificationFilters('survey-abc', false)
+ saved.events![0].properties = [...(saved.events![0].properties ?? []), customRestriction]
+
+ // Reloading between saves is what makes this bite: the restriction lands on both branches,
+ // and coming back from the API they are equal but distinct objects, so a merge that
+ // deduplicated by object identity would keep both copies and double them on every save.
+ const reload = (filters: HogFunctionType['filters']): HogFunctionType['filters'] =>
+ JSON.parse(JSON.stringify(filters))
+ let merged = mergeResponseFiltersIntoExistingFilters(
+ saved,
+ getSurveyNotificationFilters('survey-abc', false),
+ []
+ )
+ merged = mergeResponseFiltersIntoExistingFilters(
+ reload(merged),
+ getSurveyNotificationFilters('survey-abc', false),
+ []
+ )
+
+ const sentBranches = merged?.events?.filter((event) => event.id === SurveyEventName.SENT)
+ for (const sentBranch of sentBranches ?? []) {
+ const copies = (sentBranch.properties ?? []).filter(
+ (property) => 'key' in property && property.key === customRestriction.key
+ )
+ expect(copies).toHaveLength(1)
+ }
+ })
+
+ // Removing the sent branches through the full editor is how a notification is made
+ // dismissal-only. Rebuilding them unconditionally would hand it back the completed-response
+ // branches on the next unrelated save, sending exactly what the user opted out of.
+ it('leaves a dismissal-only notification without sent branches', () => {
+ const saved = getSurveyNotificationFilters('survey-abc', false)
+ saved.events = saved.events?.filter((event) => event.id === SurveyEventName.DISMISSED)
+
+ const merged = mergeResponseFiltersIntoExistingFilters(
+ saved,
+ getSurveyNotificationFilters('survey-abc', false),
+ []
+ )
+
+ expect(merged?.events?.filter((event) => event.id === SurveyEventName.SENT)).toHaveLength(0)
+ expect(merged?.events?.filter((event) => event.id === SurveyEventName.DISMISSED)).toHaveLength(1)
+ })
})
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
index dabc9bdbf717..3a37f06569c0 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
@@ -18,8 +18,8 @@ import { NEW_SURVEY } from 'scenes/surveys/constants'
import {
SurveyResponseFilter,
buildResponseFilterProperties,
+ isSurveyResponsePropertyKey,
parseResponseFiltersFromProperties,
- stripResponseFiltersFromProperties,
} from 'scenes/surveys/responseFilters'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import {
@@ -34,6 +34,7 @@ import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
import {
AnyPropertyFilter,
+ CyclotronJobFilterEvents,
CyclotronJobFiltersType,
CyclotronJobInvocationGlobals,
CyclotronJobTestInvocationResult,
@@ -449,6 +450,7 @@ async function buildSurveyNotificationPayload({
template,
destination: form.destination,
surveyId: survey.id,
+ enablePartialResponses: survey.enable_partial_responses ?? false,
form,
})
}
@@ -468,6 +470,7 @@ async function buildSurveyNotificationPayload({
destination: form.destination,
surveyName: survey.name,
surveyId: survey.id,
+ enablePartialResponses: survey.enable_partial_responses ?? false,
form,
})
}
@@ -701,12 +704,14 @@ function createSurveyNotificationPayload({
destination,
surveyName,
surveyId,
+ enablePartialResponses,
form,
}: {
template: HogFunctionTemplateType
destination: DestinationKey
surveyName?: string | null
surveyId: string
+ enablePartialResponses: boolean
form: SurveyNotificationForm
}): Partial<HogFunctionType> {
const destinationOption = DESTINATION_OPTIONS.find((option) => option.value === destination)
@@ -764,14 +769,49 @@ function createSurveyNotificationPayload({
description: subTemplate?.description ?? `Survey notification for ${destinationOption.label}`,
inputs,
inputs_schema: template.inputs_schema,
- filters: getSurveyNotificationFilters(surveyId, buildResponseFilterProperties(form.responseFilters)),
+ filters: getSurveyNotificationFilters(
+ surveyId,
+ enablePartialResponses,
+ buildResponseFilterProperties(form.responseFilters)
+ ),
hog: template.code,
icon_url: template.icon_url,
enabled: true,
}
}
-function mergeResponseFiltersIntoExistingFilters(
+// Everything this modal writes onto a sent branch. Anything else was added elsewhere, so it has
+// to survive a rebuild: per-event properties are AND'd, and dropping a restriction widens which
+// responses reach the destination.
+const MODAL_MANAGED_SENT_PROPERTY_KEYS = new Set<string>([
+ SurveyEventProperties.SURVEY_ID,
+ SurveyEventProperties.SURVEY_COMPLETED,
+])
+
+function getCustomSentProperties(
+ filters: HogFunctionType['filters']
+): NonNullable<CyclotronJobFilterEvents['properties']> {
+ // Union across every sent branch rather than the first one: a restriction added through the full
+ // editor can sit on any single branch, and per-event properties are AND'd, so losing it widens
+ // delivery. Keyed by value because the same restriction normally exists on every branch, and
+ // object identity would let copies pile up on each re-save.
+ const byValue = new Map<string, NonNullable<CyclotronJobFilterEvents['properties']>[number]>()
+ for (const event of filters?.events ?? []) {
+ if (event.id !== SurveyEventName.SENT) {
+ continue
+ }
+ for (const property of event.properties ?? []) {
+ const key = 'key' in property && typeof property.key === 'string' ? property.key : null
+ if (key !== null && (MODAL_MANAGED_SENT_PROPERTY_KEYS.has(key) || isSurveyResponsePropertyKey(key))) {
+ continue
+ }
+ byValue.set(JSON.stringify(property), property)
+ }
+ }
+ return Array.from(byValue.values())
+}
+
+export function mergeResponseFiltersIntoExistingFilters(
existingFilters: HogFunctionType['filters'],
fallbackFilters: HogFunctionType['filters'],
responseFilters: SurveyResponseFilter[]
@@ -781,25 +821,25 @@ function mergeResponseFiltersIntoExistingFilters(
return fallbackFilters
}
const responseProperties = buildResponseFilterProperties(responseFilters)
- const events = (base.events ?? []).map((event) => {
- if (event.id !== SurveyEventName.SENT) {
- return event
- }
- const preservedProperties = stripResponseFiltersFromProperties(
- (event.properties ?? []).filter(
- (property): property is EventPropertyFilter =>
- typeof property === 'object' &&
- property !== null &&
- 'type' in property &&
- (property as { type?: unknown }).type === PropertyFilterType.Event
- )
- )
- return {
- ...event,
- properties: [...preservedProperties, ...responseProperties],
- }
- })
- return { ...base, events }
+ // Sent branches are rebuilt from the freshly built filters rather than preserved, so re-saving
+ // repairs a notification stored before the completion branches were corrected. Only when the
+ // saved config already had one: a notification whose sent branches were removed through the
+ // full editor is deliberately dismissal-only, and reinstating them would widen delivery. A
+ // notification needing the repair still has its sent branch, so gating on it costs nothing.
+ const hasSavedSentBranch = (base.events ?? []).some((event) => event.id === SurveyEventName.SENT)
+ const customProperties = getCustomSentProperties(base)
+ const rebuiltSentEvents = hasSavedSentBranch
+ ? (fallbackFilters?.events ?? [])
+ .filter((event) => event.id === SurveyEventName.SENT)
+ .map(
+ (event): CyclotronJobFilterEvents => ({
+ ...event,
+ properties: [...(event.properties ?? []), ...customProperties, ...responseProperties],
+ })
+ )
+ : []
+ const preservedEvents = (base.events ?? []).filter((event) => event.id !== SurveyEventName.SENT)
+ return { ...base, events: [...rebuiltSentEvents, ...preservedEvents] }
}
function updateSurveyNotificationPayload({
@@ -807,12 +847,14 @@ function updateSurveyNotificationPayload({
template,
destination,
surveyId,
+ enablePartialResponses,
form,
}: {
notification: HogFunctionType
template: HogFunctionTemplateType
destination: DestinationKey
surveyId: string
+ enablePartialResponses: boolean
form: SurveyNotificationForm
}): Partial<HogFunctionType> {
const payload = createSurveyNotificationPayload({
@@ -820,6 +862,7 @@ function updateSurveyNotificationPayload({
destination,
surveyName: null,
surveyId,
+ enablePartialResponses,
form,
})
@@ -865,6 +908,7 @@ function createCopiedSurveyNotificationPayload({
destination,
surveyName: survey.name,
surveyId: survey.id,
+ enablePartialResponses: survey.enable_partial_responses ?? false,
form,
})
@@ -885,7 +929,11 @@ function createCopiedSurveyNotificationPayload({
},
mappings: remapSurveyResponseProperties(notification.mappings, survey),
masking: notification.masking,
- filters: getSurveyNotificationFilters(survey.id, buildResponseFilterProperties(form.responseFilters)),
+ filters: getSurveyNotificationFilters(
+ survey.id,
+ survey.enable_partial_responses ?? false,
+ buildResponseFilterProperties(form.responseFilters)
+ ),
hog: remapSurveyResponseProperties(notification.hog, survey) ?? template.code,
icon_url: notification.icon_url ?? template.icon_url,
enabled: true,
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index 6412d8586638..50b176b1abeb 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -188,7 +188,7 @@ describe('survey utils', () => {
describe('getSurveyNotificationFilters', () => {
it('builds survey-specific notification filters', () => {
- expect(getSurveyNotificationFilters('survey-123')).toEqual({
+ expect(getSurveyNotificationFilters('survey-123', true)).toEqual({
events: [
{
id: SurveyEventName.SENT,
@@ -229,6 +229,20 @@ describe('survey utils', () => {
],
})
})
+
+ it('also matches a sent event with no completion flag when partial responses are off', () => {
+ const sentBranches = getSurveyNotificationFilters('survey-123', false).events?.filter(
+ (event) => event.id === SurveyEventName.SENT
+ )
+
+ expect(sentBranches).toHaveLength(2)
+ expect(sentBranches?.[1].properties).toContainEqual({
+ key: SurveyEventProperties.SURVEY_COMPLETED,
+ type: PropertyFilterType.Event,
+ value: PropertyOperator.IsNotSet,
+ operator: PropertyOperator.IsNotSet,
+ })
+ })
})
describe('buildSurveyExampleInvocationGlobals', () => {
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index a74cb566478e..9aca95ac876f 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -1240,22 +1240,43 @@ export function getSurveyDisplayConditionsSummary(survey: Survey | NewSurvey): S
return parts
}
+/**
+ * With partial responses off, posthog-js has no partial submission to distinguish a complete one
+ * from, so it never sets `$survey_completed` and requiring `= true` matches nothing. Accept the
+ * property being absent as completed too, the same way the response summary counts them
+ * (`enable_partial_responses` branch in `ee/surveys/summaries/headline_summary.py`). An explicit
+ * `false` stays excluded: a survey switched from partial to non-partial keeps its old partials.
+ */
export function getSurveyNotificationFilters(
surveyId: string,
+ enablePartialResponses: boolean,
extraSentEventProperties: EventPropertyFilter[] = []
): CyclotronJobFiltersType {
+ const surveyIdProperty: EventPropertyFilter = {
+ key: SurveyEventProperties.SURVEY_ID,
+ type: PropertyFilterType.Event,
+ value: surveyId,
+ operator: PropertyOperator.Exact,
+ }
const sentEventProperties: EventPropertyFilter[] = [
+ surveyIdProperty,
{
- key: SurveyEventProperties.SURVEY_ID,
+ key: SurveyEventProperties.SURVEY_COMPLETED,
type: PropertyFilterType.Event,
- value: surveyId,
+ value: true,
operator: PropertyOperator.Exact,
},
+ ...extraSentEventProperties,
+ ]
+ // Event entries are OR'd, so a second branch is how "absent or true" is expressed with
+ // plain property filters rather than a hand-written HogQL predicate.
+ const completedUnsetEventProperties: EventPropertyFilter[] = [
+ surveyIdProperty,
{
key: SurveyEventProperties.SURVEY_COMPLETED,
type: PropertyFilterType.Event,
- value: true,
- operator: PropertyOperator.Exact,
+ value: PropertyOperator.IsNotSet,
+ operator: PropertyOperator.IsNotSet,
},
...extraSentEventProperties,
]
@@ -1267,6 +1288,15 @@ export function getSurveyNotificationFilters(
type: 'events',
properties: sentEventProperties,
},
+ ...(enablePartialResponses
+ ? []
+ : [
+ {
+ id: SurveyEventName.SENT,
+ type: 'events' as const,
+ properties: completedUnsetEventProperties,
+ },
+ ]),
{
id: SurveyEventName.DISMISSED,
type: 'events',