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): merge split-submission answers in the results tab (#86403)

Adam Bowkerde87c758e92b
diff --git a/frontend/src/scenes/surveys/Surveys.stories.tsx b/frontend/src/scenes/surveys/Surveys.stories.tsx
index 5b2f6cd8515a..55e8c0776eae 100644
--- a/frontend/src/scenes/surveys/Surveys.stories.tsx
+++ b/frontend/src/scenes/surveys/Surveys.stories.tsx
@@ -571,7 +571,7 @@ export const SurveyResults: Story = {
'/api/environments/:team_id/query/:kind/': async ({ request }) => {
const body = (await request.json()) as any
const sql: string = body?.query?.query ?? ''
- if (sql.includes('question_id, label, cnt')) {
+ if (body?.query?.tags?.name === 'survey_results_aggregate') {
return MOCK_SURVEY_AGGREGATE_RESULTS
}
if (sql.includes('BASE STATS')) {
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index 0de96dbc5f44..dea3a2e0b0ea 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -1858,14 +1858,14 @@ export const surveyLogic = kea<surveyLogicType>([
const survey = values.survey as Survey
const queryFilters: SurveyQueryFilters = {
timestampFilter: values.timestampFilter,
- answerFilterHogQLExpression: values.answerFilterHogQLExpression,
+ answerFilters: values.answerFilters,
archivedResponsesFilter: values.archivedResponsesFilter,
}
const queryParams = {
queryParams: { filters: { properties: values.propertyFilters } },
}
- const aggregateQuery = buildAggregateQuery(survey, queryFilters, values.dateRange)
- const openEndedResult = buildOpenEndedQuery(survey, queryFilters, values.dateRange)
+ const aggregateQuery = buildAggregateQuery(survey, queryFilters)
+ const openEndedResult = buildOpenEndedQuery(survey, queryFilters)
const startMs = performance.now()
let aggregateDuration = 0
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index d28ceea0ccc7..2aed81641f63 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -19,6 +19,8 @@ import {
} from '~/types'
import {
+ buildAggregateQuery,
+ buildOpenEndedQuery,
buildSurveyExampleInvocationGlobals,
buildPartialResponsesFilter,
buildSurveyOptionalBooleanPropertyFilter,
@@ -45,6 +47,7 @@ import {
validateCSSProperty,
validateSurveyAppearance,
} from './utils'
+import type { SurveyQueryFilters } from './utils'
jest.mock('lib/utils/getAppContext', () => ({
getAppContext: jest.fn(() => undefined),
@@ -1059,6 +1062,158 @@ describe('survey utils', () => {
})
})
+ describe('submission merging in the results queries', () => {
+ const buildSurvey = (enablePartialResponses: boolean): Survey =>
+ ({
+ id: 'test-survey-id',
+ created_at: '2024-11-19T00:00:00Z',
+ end_date: null,
+ enable_partial_responses: enablePartialResponses,
+ questions: [
+ { id: 'q-rating', type: SurveyQuestionType.Rating, question: 'How was it?' },
+ { id: 'q-open', type: SurveyQuestionType.Open, question: 'Why?' },
+ {
+ id: 'q-multi',
+ type: SurveyQuestionType.MultipleChoice,
+ question: 'Which ones?',
+ choices: ['a', 'b'],
+ },
+ ],
+ }) as Survey
+
+ const buildFilters = (survey: Survey, overrides: Partial<SurveyQueryFilters> = {}): SurveyQueryFilters => ({
+ timestampFilter: buildSurveyTimestampFilter(survey),
+ answerFilters: [],
+ archivedResponsesFilter: '',
+ ...overrides,
+ })
+
+ it.each([
+ ['rating', 0, 'isNotNull(q0_raw)'],
+ ['open', 1, 'isNotNull(q1_raw)'],
+ // Multiple-choice answers are arrays, so an `isNotNull` merge condition would be true on
+ // every event and re-elect the latest one, dropping choices made on an earlier event.
+ ['multiple choice', 2, 'length(q2_raw) > 0'],
+ ])('merges the %s answer across the submission with argMaxIf', (_type, index, presenceExpr) => {
+ const survey = buildSurvey(true)
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ expect(query).toContain(`argMaxIf(q${index}_raw, timestamp, ${presenceExpr}) AS q${index}_answer`)
+ expect(query).toContain('GROUP BY submission_key')
+ })
+
+ it('requires a completed event per submission rather than per event when partial responses are off', () => {
+ const survey = buildSurvey(false)
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ // The completed check has to run over the grouped submission. Back in the event-level
+ // WHERE it removes the partial events before their answers can be merged, which is
+ // exactly how a rating sent on its own event went missing.
+ expect(query).toContain('HAVING countIf(is_completed_event) > 0')
+ expect(query).toContain(
+ `${buildSurveyOptionalBooleanPropertyFilter(
+ SurveyEventProperties.SURVEY_COMPLETED,
+ 'false'
+ )} AS is_completed_event`
+ )
+ })
+
+ it('surfaces every submission regardless of completion when partial responses are on', () => {
+ const survey = buildSurvey(true)
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ expect(query).not.toContain('is_completed_event')
+ })
+
+ it('applies answer and archive filters to the merged answer, not to single events', () => {
+ const survey = buildSurvey(true)
+ const filters = buildFilters(survey, {
+ answerFilters: [
+ {
+ type: PropertyFilterType.Event,
+ key: '$survey_response_q-rating',
+ operator: PropertyOperator.Exact,
+ value: '2',
+ } as EventPropertyFilter,
+ ],
+ archivedResponsesFilter: "AND uuid NOT IN ('archived-uuid')",
+ })
+
+ const query = buildAggregateQuery(survey, filters)
+
+ // Filtering on the raw event expression would discard a submission whose matching
+ // answer arrived on a non-final event.
+ expect(query).toContain("(q0_answer = '2')")
+ expect(query).not.toContain("getSurveyResponse(0, 'q-rating') = '2'")
+ expect(query).toContain("uuid NOT IN ('archived-uuid')")
+ })
+
+ it('counts an unanswered optional single choice when the merge yields null instead of an empty string', () => {
+ const survey = {
+ ...buildSurvey(true),
+ questions: [
+ {
+ id: 'q-choice',
+ type: SurveyQuestionType.SingleChoice,
+ question: 'Pick one',
+ choices: ['a', 'b'],
+ optional: true,
+ },
+ ],
+ } as Survey
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ // argMaxIf returns the type default when no event answered the question, so the old
+ // `= ''` test silently missed those submissions.
+ expect(query).toContain("length(trim(coalesce(q0_answer, ''))) = 0")
+ })
+
+ it('reads the merged submissions once rather than once per question', () => {
+ const survey = buildSurvey(true)
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ // ClickHouse inlines a CTE instead of materializing it, so counting each question in
+ // its own UNION ALL branch re-runs the whole merge per branch. Measured at roughly
+ // twice the runtime on a four-question survey before this collapsed to one arrayJoin.
+ expect(query).not.toContain('UNION ALL')
+ expect(query!.match(/argMaxIf\(q0_raw/g)).toHaveLength(1)
+ })
+
+ it('does not alias the merged timestamp back onto the column the merge orders by', () => {
+ const survey = buildSurvey(true)
+
+ const query = buildAggregateQuery(survey, buildFilters(survey))
+
+ // `max(timestamp) AS timestamp` makes every sibling `argMax(..., timestamp)` resolve
+ // its ordering argument to that aggregate, and ClickHouse rejects the nesting with
+ // "Aggregate function ... is found inside another aggregate function".
+ expect(query).toContain('max(timestamp) AS submitted_at')
+ expect(query).not.toContain('max(timestamp) AS timestamp')
+ })
+
+ it('keeps respondent metadata after the open columns so positional parsing still lines up', () => {
+ const survey = buildSurvey(true)
+
+ const result = buildOpenEndedQuery(survey, buildFilters(survey))
+
+ const openColumnIndex = result!.query.indexOf('q1_answer AS q1_response')
+ expect(openColumnIndex).toBeGreaterThan(-1)
+ expect(
+ result!.query.indexOf('distinct_id,\n submitted_at,\n session_id')
+ ).toBeGreaterThan(openColumnIndex)
+ expect(result!.columnMap['q-open']).toEqual({
+ columnIndex: 0,
+ questionIndex: 1,
+ type: SurveyQuestionType.Open,
+ })
+ })
+ })
+
describe('buildSurveyOptionalBooleanPropertyFilter', () => {
it('builds a null-safe comparison for optional survey booleans', () => {
expect(
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 134d75062bdb..d082ba682937 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -401,12 +401,19 @@ export function getSurveyResponse(question: SurveyQuestion, index: number): stri
*
* @param filters - The answer filters to convert to HogQL expressions
* @param survey - The survey object (needed to access question IDs)
+ * @param resolveResponseExpr - How to address a question's answer. Defaults to the event-level
+ * `getSurveyResponse(...)` accessor. Callers querying merged submissions pass a resolver
+ * returning the merged column alias instead, since `getSurveyResponse` is not in scope there.
* @returns A HogQL expression string that can be used in queries. If there are no filters, it returns an empty string.
*
* TODO: Consider leveraging the backend query builder instead of duplicating this logic in the frontend.
* ClickHouse has powerful functions like match(), multiIf(), etc. that could be used more effectively.
*/
-export function createAnswerFilterHogQLExpression(filters: EventPropertyFilter[], survey: Survey): string {
+export function createAnswerFilterHogQLExpression(
+ filters: EventPropertyFilter[],
+ survey: Survey,
+ resolveResponseExpr: (question: SurveyQuestion, questionIndex: number) => string = getSurveyResponse
+): string {
if (!filters || !filters.length) {
return ''
}
@@ -456,41 +463,41 @@ export function createAnswerFilterHogQLExpression(filters: EventPropertyFilter[]
case 'is_not':
if (Array.isArray(filter.value)) {
const valueList = filter.value.map((v) => `'${escapeSqlString(String(v))}'`).join(', ')
- condition = `(${getSurveyResponse(question, questionIndex)} ${
+ condition = `(${resolveResponseExpr(question, questionIndex)} ${
filter.operator === 'is_not' ? 'NOT IN' : 'IN'
} (${valueList}))`
} else {
- condition = `(${getSurveyResponse(question, questionIndex)} ${
+ condition = `(${resolveResponseExpr(question, questionIndex)} ${
filter.operator === 'is_not' ? '!=' : '='
} '${escapedValue}')`
}
break
case 'icontains':
if (question.type !== SurveyQuestionType.MultipleChoice) {
- condition = `(${getSurveyResponse(question, questionIndex)} ILIKE '%${escapedValue}%')`
+ condition = `(${resolveResponseExpr(question, questionIndex)} ILIKE '%${escapedValue}%')`
} else {
- condition = `(arrayExists(x -> x ilike '%${escapedValue}%', ${getSurveyResponse(question, questionIndex)}))`
+ condition = `(arrayExists(x -> x ilike '%${escapedValue}%', ${resolveResponseExpr(question, questionIndex)}))`
}
break
case 'not_icontains':
if (question.type !== SurveyQuestionType.MultipleChoice) {
- condition = `(NOT ${getSurveyResponse(question, questionIndex)} ILIKE '%${escapedValue}%')`
+ condition = `(NOT ${resolveResponseExpr(question, questionIndex)} ILIKE '%${escapedValue}%')`
} else {
- condition = `(NOT arrayExists(x -> x ilike '%${escapedValue}%', ${getSurveyResponse(question, questionIndex)}))`
+ condition = `(NOT arrayExists(x -> x ilike '%${escapedValue}%', ${resolveResponseExpr(question, questionIndex)}))`
}
break
case 'regex':
if (question.type !== SurveyQuestionType.MultipleChoice) {
- condition = `(match(${getSurveyResponse(question, questionIndex)}, '${escapedValue}'))`
+ condition = `(match(${resolveResponseExpr(question, questionIndex)}, '${escapedValue}'))`
} else {
- condition = `(arrayExists(x -> match(x, '${escapedValue}'), ${getSurveyResponse(question, questionIndex)}))`
+ condition = `(arrayExists(x -> match(x, '${escapedValue}'), ${resolveResponseExpr(question, questionIndex)}))`
}
break
case 'not_regex':
if (question.type !== SurveyQuestionType.MultipleChoice) {
- condition = `(NOT match(${getSurveyResponse(question, questionIndex)}, '${escapedValue}'))`
+ condition = `(NOT match(${resolveResponseExpr(question, questionIndex)}, '${escapedValue}'))`
} else {
- condition = `(NOT arrayExists(x -> match(x, '${escapedValue}'), ${getSurveyResponse(question, questionIndex)}))`
+ condition = `(NOT arrayExists(x -> match(x, '${escapedValue}'), ${resolveResponseExpr(question, questionIndex)}))`
}
break
// Add more operators as needed
@@ -687,10 +694,146 @@ export function buildPartialResponsesFilter(survey: Survey, dateRange?: SurveyDa
export interface SurveyQueryFilters {
timestampFilter: string
- answerFilterHogQLExpression: string
+ answerFilters: EventPropertyFilter[]
archivedResponsesFilter: string
}
+/**
+ * HogQL expression collapsing a submission's `survey sent` events into one group. An event with
+ * no `$survey_submission_id` is keyed by its own uuid, so it stays a distinct response the way it
+ * did before submission IDs existed.
+ *
+ * Must stay identical to `SUBMISSION_GROUPING_KEY` in
+ * `products/surveys/backend/responses/fetch_rows.py`, otherwise the Results tab and the responses
+ * API disagree about what counts as one submission.
+ */
+const SUBMISSION_GROUPING_KEY = `if(
+ coalesce(properties.\`${SurveyEventProperties.SURVEY_SUBMISSION_ID}\`, '') = '',
+ toString(uuid),
+ properties.\`${SurveyEventProperties.SURVEY_SUBMISSION_ID}\`
+)`
+
+/** Alias holding a question's merged answer in the submission-merge subquery. */
+function mergedAnswerAlias(questionIndex: number): string {
+ return `q${questionIndex}_answer`
+}
+
+/** Alias holding a question's raw per-event answer in the submission-merge subquery. */
+function rawAnswerAlias(questionIndex: number): string {
+ return `q${questionIndex}_raw`
+}
+
+/**
+ * True when the event actually carries an answer to this question, so the merge can pick the event
+ * that answered it rather than whichever event in the submission happens to be latest.
+ *
+ * Multiple-choice answers are arrays, which are never null, so they need a length check instead.
+ */
+function buildAnswerPresenceExpr(rawAlias: string, question: SurveyQuestion): string {
+ return question.type === SurveyQuestionType.MultipleChoice ? `length(${rawAlias}) > 0` : `isNotNull(${rawAlias})`
+}
+
+/** True when the merged answer holds no content, covering both the null and empty-string cases. */
+export function buildAnswerIsEmptyExpr(mergedAlias: string, question: SurveyQuestion): string {
+ return question.type === SurveyQuestionType.MultipleChoice
+ ? `length(${mergedAlias}) = 0`
+ : `length(trim(coalesce(${mergedAlias}, ''))) = 0`
+}
+
+interface QuestionWithIndex {
+ question: SurveyQuestion
+ index: number
+}
+
+/**
+ * Builds a subquery emitting one row per submission, with every question's answer merged across
+ * that submission's events.
+ *
+ * A submission can span several `survey sent` events that don't each repeat the answers given
+ * earlier. The AI feedback flow produces exactly that shape: the rating arrives on one event and
+ * the free-text follow-up on another, joined by `$survey_submission_id`. Electing a single event
+ * per submission therefore drops every answer that only ever lived on a non-elected event, which
+ * is why this merges per question with `argMaxIf` instead, keeping the latest answer to each.
+ *
+ * This mirrors the responses API in `products/surveys/backend/responses/fetch_rows.py`, including
+ * its use of `isNotNull` rather than a stricter emptiness test, so both surfaces resolve a
+ * re-answered question the same way.
+ */
+function buildMergedSubmissionsSubquery(
+ survey: Survey,
+ filters: SurveyQueryFilters,
+ questions: QuestionWithIndex[],
+ { includeRespondentMetadata = false }: { includeRespondentMetadata?: boolean } = {}
+): string {
+ // With partial responses off, only completed submissions may surface. That check has to run
+ // against the whole submission rather than a single event, because the answers still need
+ // merging from the partial events that led up to the completed one.
+ const requiresCompletedEvent = !survey.enable_partial_responses
+ const completedEventExpr = buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')
+
+ const innerColumns = [
+ 'uuid',
+ 'timestamp',
+ ...(includeRespondentMetadata ? ['distinct_id', 'properties.`$session_id` AS session_id'] : []),
+ ...(requiresCompletedEvent ? [`${completedEventExpr} AS is_completed_event`] : []),
+ ...questions.map(({ question, index }) => `${getSurveyResponse(question, index)} AS ${rawAnswerAlias(index)}`),
+ `${SUBMISSION_GROUPING_KEY} AS submission_key`,
+ ]
+
+ const outerColumns = [
+ 'argMax(uuid, timestamp) AS uuid',
+ // Aliased away from `timestamp` because every other aggregate here orders by that column,
+ // and an alias of the same name would resolve to this aggregate instead, nesting them.
+ 'max(timestamp) AS submitted_at',
+ ...(includeRespondentMetadata
+ ? ['argMax(distinct_id, timestamp) AS distinct_id', 'argMax(session_id, timestamp) AS session_id']
+ : []),
+ ...questions.map(({ question, index }) => {
+ const raw = rawAnswerAlias(index)
+ return `argMaxIf(${raw}, timestamp, ${buildAnswerPresenceExpr(raw, question)}) AS ${mergedAnswerAlias(index)}`
+ }),
+ ]
+
+ // Answer and archive filters read the merged answer, so they belong in HAVING. The archive
+ // filter names `uuid`, which resolves to the representative uuid aliased above — the same one
+ // the responses table archives.
+ const havingConditions: string[] = []
+ if (requiresCompletedEvent) {
+ havingConditions.push('countIf(is_completed_event) > 0')
+ }
+ const mergedAnswerFilter = createAnswerFilterHogQLExpression(filters.answerFilters, survey, (_, index) =>
+ mergedAnswerAlias(index)
+ )
+ if (mergedAnswerFilter !== '') {
+ havingConditions.push(stripLeadingAnd(mergedAnswerFilter))
+ }
+ if (filters.archivedResponsesFilter !== '') {
+ havingConditions.push(stripLeadingAnd(filters.archivedResponsesFilter))
+ }
+
+ return `SELECT ${outerColumns.join(',\n ')}
+ FROM (
+ SELECT ${innerColumns.join(',\n ')}
+ FROM events
+ WHERE event = '${SurveyEventName.SENT}'
+ AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${survey.id}'
+ ${filters.timestampFilter}
+ AND {filters}
+ )
+ GROUP BY submission_key${havingConditions.length > 0 ? `\n HAVING ${havingConditions.join(' AND ')}` : ''}`
+}
+
+function stripLeadingAnd(expression: string): string {
+ return expression.replace(/^\s*AND\s+/, '')
+}
+
+/** Questions that can hold an answer. Link questions never produce a response. */
+function getAnswerableQuestions(survey: Survey): QuestionWithIndex[] {
+ return survey.questions
+ .map((question, index) => ({ question, index }))
+ .filter(({ question }) => !!question.id && question.type !== SurveyQuestionType.Link)
+}
+
export interface OpenEndedColumnMap {
[questionId: string]: {
columnIndex: number
@@ -699,97 +842,83 @@ export interface OpenEndedColumnMap {
}
}
-export function buildAggregateQuery(
- survey: Survey,
- filters: SurveyQueryFilters,
- dateRange?: SurveyDateRange | null
-): string | null {
- const dedupFilter = buildPartialResponsesFilter(survey, dateRange)
- const branches: string[] = []
-
- const baseWhere = `event = '${SurveyEventName.SENT}'
- AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${survey.id}'
- ${filters.timestampFilter}
- ${filters.answerFilterHogQLExpression}
- ${filters.archivedResponsesFilter}
- ${dedupFilter}
- AND {filters}`
-
- for (const [index, question] of survey.questions.entries()) {
- if (!question.id || question.type === SurveyQuestionType.Link) {
- continue
- }
+export function buildAggregateQuery(survey: Survey, filters: SurveyQueryFilters): string | null {
+ const questions = getAnswerableQuestions(survey)
+ if (questions.length === 0) {
+ return null
+ }
- const responseExpr = getSurveyResponse(question, index)
+ // Each entry emits the (question_id, label) pairs one submission contributes to one question.
+ // They are concatenated and unrolled with a single arrayJoin so the merge below is read once,
+ // rather than once per question: a ClickHouse CTE is inlined, so a UNION ALL branch per
+ // question would re-run the whole merge per branch.
+ const labelPairs: string[] = []
+ const noPairs = '[]'
+
+ for (const { question, index } of questions) {
+ const answer = mergedAnswerAlias(index)
+ const questionId = `'${question.id}'`
+ // The merged answer is nullable, and a nullable label would not match the literal pairs
+ // below when the arrays are concatenated.
+ const answerLabel = `coalesce(toString(${answer}), '')`
if (question.type === SurveyQuestionType.Rating || question.type === SurveyQuestionType.SingleChoice) {
- branches.push(`SELECT '${question.id}' AS question_id,
- ${responseExpr} AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere} AND isNotNull(${responseExpr})
- GROUP BY label`)
+ labelPairs.push(`if(isNotNull(${answer}), [(${questionId}, ${answerLabel})], ${noPairs})`)
if (question.type === SurveyQuestionType.SingleChoice && question.optional) {
- branches.push(`SELECT '${question.id}' AS question_id,
- '__no_response__' AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere} AND ${responseExpr} = ''`)
+ labelPairs.push(
+ `if(${buildAnswerIsEmptyExpr(answer, question)}, [(${questionId}, '__no_response__')], ${noPairs})`
+ )
}
} else if (question.type === SurveyQuestionType.MultipleChoice) {
- branches.push(`SELECT '${question.id}' AS question_id,
- trim(BOTH '"\\'' FROM arrayJoin(${responseExpr})) AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere}
- GROUP BY label HAVING isNotNull(label) AND label != ''`)
-
- branches.push(`SELECT '${question.id}' AS question_id,
- '__total__' AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere} AND length(${responseExpr}) > 0`)
+ labelPairs.push(
+ `arrayMap(choice -> (${questionId}, choice),
+ arrayFilter(choice -> choice != '',
+ arrayMap(choice -> trim(BOTH '"\\'' FROM choice), ${answer})))`
+ )
+ labelPairs.push(`if(length(${answer}) > 0, [(${questionId}, '__total__')], ${noPairs})`)
if (question.optional) {
- branches.push(`SELECT '${question.id}' AS question_id,
- '__no_response__' AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere} AND length(${responseExpr}) = 0`)
+ labelPairs.push(`if(length(${answer}) = 0, [(${questionId}, '__no_response__')], ${noPairs})`)
}
} else if (question.type === SurveyQuestionType.Open) {
- branches.push(`SELECT '${question.id}' AS question_id,
- '__total__' AS label,
- count() AS cnt
- FROM events
- WHERE ${baseWhere} AND isNotNull(${responseExpr})`)
+ labelPairs.push(`if(isNotNull(${answer}), [(${questionId}, '__total__')], ${noPairs})`)
}
}
- if (branches.length === 0) {
+ if (labelPairs.length === 0) {
return null
}
- return `SELECT question_id, label, cnt FROM (${branches.join('\nUNION ALL\n')}) LIMIT 50000`
+ const mergedSubmissions = buildMergedSubmissionsSubquery(survey, filters, questions)
+
+ return `SELECT
+ tupleElement(question_label, 1) AS question_id,
+ tupleElement(question_label, 2) AS label,
+ count() AS cnt
+ FROM (
+ SELECT arrayJoin(arrayConcat(
+ ${labelPairs.join(',\n ')}
+ )) AS question_label
+ FROM (
+ ${mergedSubmissions}
+ )
+ )
+ GROUP BY question_id, label
+ LIMIT 50000`
}
export function buildOpenEndedQuery(
survey: Survey,
filters: SurveyQueryFilters,
- dateRange?: SurveyDateRange | null,
limit: number = 50000
): { query: string; columnMap: OpenEndedColumnMap } | null {
- const dedupFilter = buildPartialResponsesFilter(survey, dateRange)
+ const questions = getAnswerableQuestions(survey)
const openColumns: string[] = []
const columnMap: OpenEndedColumnMap = {}
let columnIndex = 0
- for (const [index, question] of survey.questions.entries()) {
- if (!question.id || question.type === SurveyQuestionType.Link) {
- continue
- }
-
+ for (const { question, index } of questions) {
const isOpen = question.type === SurveyQuestionType.Open
const hasOpenChoice =
(question.type === SurveyQuestionType.SingleChoice ||
@@ -797,8 +926,8 @@ export function buildOpenEndedQuery(
(question as MultipleSurveyQuestion).hasOpenChoice
if (isOpen || hasOpenChoice) {
- openColumns.push(`${getSurveyResponse(question, index)} AS q${index}_response`)
- columnMap[question.id] = { columnIndex, questionIndex: index, type: question.type }
+ openColumns.push(`${mergedAnswerAlias(index)} AS q${index}_response`)
+ columnMap[question.id!] = { columnIndex, questionIndex: index, type: question.type }
columnIndex++
}
}
@@ -807,20 +936,23 @@ export function buildOpenEndedQuery(
return null
}
+ // The merge needs every answerable question, not just the open ones, because answer filters in
+ // HAVING can reference a question that has no open column of its own.
+ const mergedSubmissions = buildMergedSubmissionsSubquery(survey, filters, questions, {
+ includeRespondentMetadata: true,
+ })
+
+ // Column order stays open columns, then distinct_id, timestamp, session_id — processOpenEndedResults
+ // reads the metadata positionally from the end.
const query = `SELECT
${openColumns.join(',\n')},
- events.distinct_id,
- events.timestamp,
- events.properties.$session_id
- FROM events
- WHERE event = '${SurveyEventName.SENT}'
- AND properties.${SurveyEventProperties.SURVEY_ID} = '${survey.id}'
- ${filters.timestampFilter}
- ${filters.answerFilterHogQLExpression}
- ${filters.archivedResponsesFilter}
- ${dedupFilter}
- AND {filters}
- ORDER BY events.timestamp DESC
+ distinct_id,
+ submitted_at,
+ session_id
+ FROM (
+ ${mergedSubmissions}
+ )
+ ORDER BY submitted_at DESC
LIMIT ${limit}`
return { query, columnMap }
diff --git a/products/ai_observability/frontend/feedback-view/wizard/feedbackSurveyWizardLogic.ts b/products/ai_observability/frontend/feedback-view/wizard/feedbackSurveyWizardLogic.ts
index e5146dbefb97..fddf93d7fd92 100644
--- a/products/ai_observability/frontend/feedback-view/wizard/feedbackSurveyWizardLogic.ts
+++ b/products/ai_observability/frontend/feedback-view/wizard/feedbackSurveyWizardLogic.ts
@@ -257,6 +257,11 @@ export const feedbackSurveyWizardLogic = kea<feedbackSurveyWizardLogicType>([
questions,
appearance: followUpEnabled ? appearance : undefined,
start_date: dayjs().toISOString(),
+ // The capture snippet this wizard hands out sends the rating and the
+ // follow-up text as two separate events, and a rating on its own is
+ // already usable feedback. Without this, a submission that never reaches
+ // the follow-up counts as incomplete and is hidden from the results.
+ enable_partial_responses: true,
})
eventUsageLogic.actions.reportSurveyCreated(survey, false, 'llm_analytics')