: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
fix(surveys): match translated choices in response queries (#66701)
Ben Leaa60558ebb411
diff --git a/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx b/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsxindex 591ebea39b5c..487f22ae0f3b 100644--- a/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx+++ b/frontend/src/scenes/surveys/SurveyEditQuestionRow.tsx@@ -23,7 +23,13 @@ import {} from '~/types'import { ValidationRulesEditor } from './components/ValidationRulesEditor'-import { NewSurvey, SCALE_OPTIONS, SURVEY_RATING_SCALE, SurveyQuestionLabel } from './constants'+import {+ NewSurvey,+ SCALE_OPTIONS,+ SURVEY_RATING_SCALE,+ SurveyQuestionLabel,+ TRANSLATION_NEEDED_PLACEHOLDER,+} from './constants'import { HTMLEditor } from './SurveyAppearanceUtils'import { SurveyDragHandle } from './SurveyDragHandle'import { surveyLogic } from './surveyLogic'@@ -266,7 +272,7 @@ export function SurveyEditQuestionGroup({ index, question }: { index: number; qureturn transChoices[newIndex]}// New or modified choices must be translated explicitly.- return '[Translation needed]'+ return TRANSLATION_NEEDED_PLACEHOLDER})updatedTranslations[lang] = {...trans,diff --git a/frontend/src/scenes/surveys/constants.tsx b/frontend/src/scenes/surveys/constants.tsxindex 10bb5e3f3ee8..b1155f7cd11e 100644--- a/frontend/src/scenes/surveys/constants.tsx+++ b/frontend/src/scenes/surveys/constants.tsx@@ -27,6 +27,10 @@ export const LINK_PAGE_SIZE = 100// which caps the generated iteration windows (and the API enforces the same limit).export const MAX_ITERATION_COUNT = 500+// Stamped into a translation's choices/text fields when the editor auto-fills a spot that needs+// a human translation. Must never be treated as real translated content.+export const TRANSLATION_NEEDED_PLACEHOLDER = '[Translation needed]'+export const SurveyQuestionLabel: Record<SurveyQuestionType, string> = {[SurveyQuestionType.Open]: 'Freeform text',[SurveyQuestionType.Rating]: 'Rating',diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.tsindex 95ec3ba3cb22..23ba1c920d8f 100644--- a/frontend/src/scenes/surveys/surveyLogic.test.ts+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts@@ -2257,6 +2257,96 @@ describe('processResultsForSurveyQuestions', () => {})})+ describe('Translated Choices', () => {+ it('aggregates translated responses under their base-language choice', () => {+ const questions = [+ {+ id: 'multi-q1',+ type: SurveyQuestionType.MultipleChoice as const,+ question: 'Pick many',+ choices: ['Analytics', 'Feature Flags'],+ translations: {+ 'zh-cn': { choices: ['分析', '功能标记'] },+ },+ },+ ]+ const rows: [string, string, number][] = [+ ['multi-q1', 'Analytics', 2],+ ['multi-q1', '分析', 3],+ ['multi-q1', '功能标记', 1],+ ['multi-q1', 'Something else', 1],+ ['multi-q1', '__total__', 7],+ ]++ const processed = processResultsForSurveyQuestions(questions, rows)+ const multiData = processed['multi-q1'] as ChoiceQuestionProcessedResponses++ const dataMap = new Map(multiData.data.map((item) => [item.label, item]))+ expect(dataMap.get('Analytics')).toEqual({ label: 'Analytics', value: 5, isPredefined: true })+ expect(dataMap.get('Feature Flags')).toEqual({ label: 'Feature Flags', value: 1, isPredefined: true })+ expect(dataMap.get('Something else')).toEqual({ label: 'Something else', value: 1, isPredefined: false })+ // The translated label is folded into the base choice, not surfaced on its own.+ expect(dataMap.has('分析')).toBe(false)+ })++ it('keeps base-language matching when a translation reuses another base choice', () => {+ const questions = [+ {+ id: 'single-q1',+ type: SurveyQuestionType.SingleChoice as const,+ question: 'Pick one',+ choices: ['Yes', 'No'],+ // A translator reused the English "Yes" for the second option — it must not+ // remap base "Yes" responses onto "No".+ translations: {+ fr: { choices: ['Oui', 'Yes'] },+ },+ },+ ]+ const rows: [string, string, number][] = [+ ['single-q1', 'Yes', 3],+ ['single-q1', 'Oui', 2],+ ]++ const processed = processResultsForSurveyQuestions(questions, rows)+ const singleData = processed['single-q1'] as ChoiceQuestionProcessedResponses++ const dataMap = new Map(singleData.data.map((item) => [item.label, item]))+ expect(dataMap.get('Yes')).toEqual({ label: 'Yes', value: 5, isPredefined: true })+ expect(dataMap.get('No')).toEqual({ label: 'No', value: 0, isPredefined: true })+ })++ it('falls back to base-only matching when the translation array length is out of sync', () => {+ const questions = [+ {+ id: 'single-q1',+ type: SurveyQuestionType.SingleChoice as const,+ question: 'Pick one',+ choices: ['Yes', 'No', 'Maybe'],+ // A choice was removed from the base without updating the translation, so the+ // arrays no longer align by position. Positional mapping is unsafe here — a+ // translated answer must NOT be silently folded into the wrong base choice.+ translations: {+ fr: { choices: ['Oui', 'Non'] },+ },+ },+ ]+ const rows: [string, string, number][] = [+ ['single-q1', 'Yes', 3],+ ['single-q1', 'Oui', 2],+ ]++ const processed = processResultsForSurveyQuestions(questions, rows)+ const singleData = processed['single-q1'] as ChoiceQuestionProcessedResponses++ const dataMap = new Map(singleData.data.map((item) => [item.label, item]))+ // Base answers still match; the translated answer surfaces as its own "Other" row+ // rather than being misattributed to a base choice.+ expect(dataMap.get('Yes')).toEqual({ label: 'Yes', value: 3, isPredefined: true })+ expect(dataMap.get('Oui')).toEqual({ label: 'Oui', value: 2, isPredefined: false })+ })+ })+describe('Open Questions', () => {it('returns total count with empty data (raw data comes from open-ended query)', () => {const questions = [@@ -2405,6 +2495,35 @@ describe('processOpenEndedResults', () => {expect(choiceData.data[0].label).toBe('Custom text')})+ it('does not collect translated predefined choices as "Other" text', () => {+ const questions = [+ {+ id: 'choice-q1',+ type: SurveyQuestionType.SingleChoice as const,+ question: 'Pick one',+ choices: ['Yes', 'No', 'Other'],+ hasOpenChoice: true,+ translations: {+ 'zh-cn': { choices: ['是', '否', '其他'] },+ },+ },+ ]+ const columnMap: OpenEndedColumnMap = {+ 'choice-q1': { columnIndex: 0, questionIndex: 0, type: SurveyQuestionType.SingleChoice },+ }+ const rows = [+ ['是', 'user1', '2024-01-15T10:00:00Z'],+ ['我自己的理由', 'user2', '2024-01-15T11:00:00Z'],+ ]++ const result = processOpenEndedResults(questions, columnMap, rows)+ const choiceData = result['choice-q1'] as ChoiceQuestionProcessedResponses++ // Only the genuinely free-text answer is collected; the translated "Yes" is recognised.+ expect(choiceData.data).toHaveLength(1)+ expect(choiceData.data[0].label).toBe('我自己的理由')+ })+it('returns empty object for null rows', () => {expect(processOpenEndedResults([], {}, null)).toEqual({})})@@ -2538,4 +2657,57 @@ describe('mergeResponsesByQuestion', () => {const merged = mergeResponsesByQuestion({}, openEnded)expect(merged['open-q']).toEqual(openEnded['open-q'])})++ it('folds a translated predefined choice into its base choice end-to-end and keeps only free-text Other rows', () => {+ const questions = [+ {+ id: 'choice-q1',+ type: SurveyQuestionType.SingleChoice as const,+ question: 'Pick one',+ choices: ['Yes', 'No', 'Other'],+ hasOpenChoice: true,+ translations: {+ 'zh-cn': { choices: ['是', '否', '其他'] },+ },+ },+ ]++ // Aggregate query result: the Chinese "是" answer folds into base "Yes".+ const aggregateRows: [string, string, number][] = [+ ['choice-q1', 'Yes', 2],+ ['choice-q1', '是', 1],+ ['choice-q1', 'No', 1],+ ['choice-q1', '__total__', 4],+ ]+ const aggregate = processResultsForSurveyQuestions(questions, aggregateRows)++ // Open-ended query result: same rows, used to recover raw "Other" text.+ const columnMap: OpenEndedColumnMap = {+ 'choice-q1': { columnIndex: 0, questionIndex: 0, type: SurveyQuestionType.SingleChoice },+ }+ const openEndedRows = [+ ['Yes', 'user1', '2024-01-15T10:00:00Z'],+ ['是', 'user2', '2024-01-15T11:00:00Z'],+ ['No', 'user3', '2024-01-15T12:00:00Z'],+ ['My own reason', 'user4', '2024-01-15T13:00:00Z'],+ ]+ const openEnded = processOpenEndedResults(questions, columnMap, openEndedRows)++ const merged = mergeResponsesByQuestion(aggregate, openEnded)+ const result = merged['choice-q1'] as ChoiceQuestionProcessedResponses++ const predefined = result.data.filter((d) => d.isPredefined)+ expect(predefined).toEqual(+ expect.arrayContaining([+ { label: 'Yes', value: 3, isPredefined: true },+ { label: 'No', value: 1, isPredefined: true },+ ])+ )++ // Only the genuinely free-text answer surfaces as "Other" — the translated "Yes" pick+ // must not leak in as its own Other row.+ const other = result.data.filter((d) => !d.isPredefined)+ expect(other).toHaveLength(1)+ expect(other[0].label).toBe('My own reason')+ })})diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsxindex 7f6d45f5bd8e..0de96dbc5f44 100644--- a/frontend/src/scenes/surveys/surveyLogic.tsx+++ b/frontend/src/scenes/surveys/surveyLogic.tsx@@ -119,11 +119,13 @@ import {NewSurvey,SURVEY_CREATED_SOURCE,SURVEY_RATING_SCALE,+ TRANSLATION_NEEDED_PLACEHOLDER,defaultSurveyAppearance,defaultSurveyFieldValues,} from './constants'import { getSurveyStatus, surveysLogic } from './surveysLogic'import type { SurveyDataState } from './surveysLogic'+import { buildChoiceTranslationMap } from './surveyTranslationUtils'import { SurveyFeatureWarning, getSurveyWarnings } from './surveyVersionRequirements'import type { TeamSdkVersions } from './surveyVersionRequirements'import {@@ -390,20 +392,26 @@ function processChoiceQuestion(): ChoiceQuestionProcessedResponses {const totalEntry = entries.find(([l]) => l === '__total__')const dataEntries = entries.filter(([l]) => l !== '__total__')- const predefined = new Set(question.choices ?? [])+ const choiceMap = buildChoiceTranslationMap(question)let total = 0const noResponseEntry = entries.find(([l]) => l === '__no_response__')const noResponseCount = noResponseEntry ? noResponseEntry[1] : 0const filteredEntries = dataEntries.filter(([l]) => l !== '__no_response__')- const data: ChoiceQuestionResponseData[] = filteredEntries- .map(([label, count]) => {- if (questionType === SurveyQuestionType.SingleChoice) {- total += count- }- return { label, value: count, isPredefined: predefined.has(label) }- })+ // Normalise each response to its base-language choice so answers given in different+ // languages aggregate under one option instead of splitting into separate rows.+ const countsByLabel = new Map<string, number>()+ for (const [label, count] of filteredEntries) {+ const normalizedLabel = choiceMap.get(label) ?? label+ countsByLabel.set(normalizedLabel, (countsByLabel.get(normalizedLabel) ?? 0) + count)+ if (questionType === SurveyQuestionType.SingleChoice) {+ total += count+ }+ }++ const data: ChoiceQuestionResponseData[] = [...countsByLabel.entries()]+ .map(([label, value]) => ({ label, value, isPredefined: choiceMap.has(label) })).sort((a, b) => b.value - a.value)if (questionType === SurveyQuestionType.MultipleChoice && totalEntry) {@@ -536,7 +544,7 @@ function collectOpenChoiceResponses(distinctIdIdx: number,timestampIdx: number): ChoiceQuestionResponseData[] {- const predefined = new Set(question.choices ?? [])+ const choiceMap = buildChoiceTranslationMap(question)const otherData: ChoiceQuestionResponseData[] = []for (const row of rows) {@@ -554,7 +562,7 @@ function collectOpenChoiceResponses(}for (const choice of choices) {- if (choice && !predefined.has(choice)) {+ if (choice && !choiceMap.has(choice)) {otherData.push({label: choice,value: 1,@@ -3416,12 +3424,12 @@ export const surveyLogic = kea<surveyLogicType>([const defaultHasValue =defaultValue && typeof defaultValue === 'string' && defaultValue.trim() !== ''- if (value === '[Translation needed]') {+ if (value === TRANSLATION_NEEDED_PLACEHOLDER) {errors.push({language: lang,questionIndex: -1,field: key,- error: 'Contains placeholder "[Translation needed]"',+ error: `Contains placeholder "${TRANSLATION_NEEDED_PLACEHOLDER}"`,})}// Only validate empty translation strings if default has a value@@ -3517,12 +3525,12 @@ export const surveyLogic = kea<surveyLogicType>([const defaultHasValue =defaultValue && typeof defaultValue === 'string' && defaultValue.trim() !== ''- if (value === '[Translation needed]') {+ if (value === TRANSLATION_NEEDED_PLACEHOLDER) {errors.push({language: lang,questionIndex: qIndex,field: key,- error: 'Contains placeholder "[Translation needed]"',+ error: `Contains placeholder "${TRANSLATION_NEEDED_PLACEHOLDER}"`,})}// Only validate empty translation strings if default has a value@@ -3546,12 +3554,12 @@ export const surveyLogic = kea<surveyLogicType>([const linkDefaultHasValue = typeof question.link === 'string' && question.link.trim() !== ''const linkValue = trans.link- if (linkValue === '[Translation needed]') {+ if (linkValue === TRANSLATION_NEEDED_PLACEHOLDER) {errors.push({language: lang,questionIndex: qIndex,field: 'link',- error: 'Contains placeholder "[Translation needed]"',+ error: `Contains placeholder "${TRANSLATION_NEEDED_PLACEHOLDER}"`,})} else if (typeof linkValue === 'string') {const trimmedLink = linkValue.trim()@@ -3577,12 +3585,12 @@ export const surveyLogic = kea<surveyLogicType>([// Check choices arrayif (isChoiceSurveyQuestion(question) && trans.choices && Array.isArray(trans.choices)) {trans.choices.forEach((choice, choiceIndex) => {- if (choice === '[Translation needed]') {+ if (choice === TRANSLATION_NEEDED_PLACEHOLDER) {errors.push({language: lang,questionIndex: qIndex,field: `choices[${choiceIndex}]`,- error: 'Contains placeholder "[Translation needed]"',+ error: `Contains placeholder "${TRANSLATION_NEEDED_PLACEHOLDER}"`,})}if (typeof choice === 'string' && choice.trim() === '') {diff --git a/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts b/frontend/src/scenes/surveys/surveyTranslationUtils.test.tsindex 5f51cfa0f0f3..e479e31813f6 100644--- a/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts+++ b/frontend/src/scenes/surveys/surveyTranslationUtils.test.ts@@ -9,7 +9,7 @@ import {SurveyType,} from '~/types'-import { getSurveyWithTranslatedContent } from './surveyTranslationUtils'+import { buildChoiceTranslationMap, getSurveyWithTranslatedContent } from './surveyTranslationUtils'const createSurvey = (): Survey => ({id: 'test-survey',@@ -123,3 +123,62 @@ describe('getSurveyWithTranslatedContent', () => {expect(getSurveyWithTranslatedContent(survey, null)).toBe(survey)})})++describe('buildChoiceTranslationMap', () => {+ const baseQuestion = (overrides: Partial<MultipleSurveyQuestion> = {}): MultipleSurveyQuestion => ({+ type: SurveyQuestionType.SingleChoice,+ question: 'Pick one',+ choices: ['yes', 'no'],+ ...overrides,+ })++ it.each([+ [+ 'maps each translation back to its base choice',+ baseQuestion({ translations: { 'zh-cn': { choices: ['是', '否'] } } }),+ { 是: 'yes', 否: 'no', yes: 'yes', no: 'no' },+ ],+ [+ 'merges multiple languages',+ baseQuestion({+ translations: { 'zh-cn': { choices: ['是', '否'] }, fr: { choices: ['oui', 'non'] } },+ }),+ { 是: 'yes', 否: 'no', oui: 'yes', non: 'no', yes: 'yes', no: 'no' },+ ],+ [+ 'keeps base choices winning over a translation reusing another base choice',+ baseQuestion({ translations: { fr: { choices: ['oui', 'yes'] } } }),+ { oui: 'yes', yes: 'yes', no: 'no' },+ ],+ [+ 'skips a translation whose choices array length is out of sync',+ baseQuestion({ choices: ['yes', 'no', 'maybe'], translations: { fr: { choices: ['oui', 'non'] } } }),+ { yes: 'yes', no: 'no', maybe: 'maybe' },+ ],+ [+ 'never maps the "[Translation needed]" placeholder',+ baseQuestion({ translations: { fr: { choices: ['[Translation needed]', 'non'] } } }),+ { non: 'no', yes: 'yes', no: 'no' },+ ],+ [+ 'never maps an empty or whitespace-only translated choice',+ baseQuestion({ translations: { fr: { choices: ['', ' '] } } }),+ { yes: 'yes', no: 'no' },+ ],+ [+ // By far the common case — an untranslated choice question must still map its own+ // choices, otherwise every answer gets treated as free-text "Other".+ 'seeds base choices for a question with no translations',+ baseQuestion(),+ { yes: 'yes', no: 'no' },+ ],+ [+ 'seeds base choices when translations is null',+ baseQuestion({ translations: null }),+ { yes: 'yes', no: 'no' },+ ],+ ['returns only an empty map for a question with no choices', baseQuestion({ choices: [] }), {}],+ ])('%s', (_name, question, expected) => {+ expect(buildChoiceTranslationMap(question)).toEqual(new Map(Object.entries(expected)))+ })+})diff --git a/frontend/src/scenes/surveys/surveyTranslationUtils.ts b/frontend/src/scenes/surveys/surveyTranslationUtils.tsindex c424dcfc045f..fe6f3cc74c4e 100644--- a/frontend/src/scenes/surveys/surveyTranslationUtils.ts+++ b/frontend/src/scenes/surveys/surveyTranslationUtils.ts@@ -1,6 +1,45 @@-import { Survey, SurveyAppearance, SurveyQuestion, SurveyQuestionType } from '~/types'+import { MultipleSurveyQuestion, Survey, SurveyAppearance, SurveyQuestion, SurveyQuestionType } from '~/types'-import { NewSurvey } from './constants'+import { NewSurvey, TRANSLATION_NEEDED_PLACEHOLDER } from './constants'++// Respondents are shown choices in their own language and submit the translated text, so a+// translated choice has to map back to its base-language choice (matched by position) to be+// recognised as a predefined answer rather than a free-text "Other" response.+//+// Keep in sync with the backend twin `build_choice_translation_map` in+// products/surveys/backend/responses/fetch_rows.py — both must agree on the positional mapping,+// the length guard, and the base-choice-wins seeding order.+export function buildChoiceTranslationMap(question: MultipleSurveyQuestion): Map<string, string> {+ const baseChoices = question.choices ?? []+ const map = new Map<string, string>()++ for (const translation of Object.values(question.translations ?? {})) {+ const translatedChoices = translation.choices+ // The length guard only catches out-of-band edits (API/Max tool) that change array+ // length — the editor path preserves length and stamps the placeholder instead (see the+ // placeholder skip below), which is why that skip is the real guard for that path.+ if (!translatedChoices || translatedChoices.length !== baseChoices.length) {+ continue+ }+ translatedChoices.forEach((choice, index) => {+ const baseChoice = baseChoices[index]+ const isUntranslated = !choice || choice === TRANSLATION_NEEDED_PLACEHOLDER || choice.trim() === ''+ // Skip untranslated placeholders and blanks — they carry no real mapping and would+ // otherwise collapse onto whichever base choice the last language lands on.+ if (!isUntranslated && baseChoice !== undefined) {+ map.set(choice, baseChoice)+ }+ })+ }++ // Seed base choices last so they take precedence: a translation that reuses another+ // base-choice string must not remap that base choice to a different option. The tradeoff is+ // lossy — a translated pick that collides with a different base choice is attributed to that+ // base option — but it's the safe default (base-language data is never misattributed).+ baseChoices.forEach((choice) => map.set(choice, choice))++ return map+}export function getSurveyWithTranslatedContent<TSurvey extends Survey | NewSurvey>(survey: TSurvey,diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex edae32e11785..715f65921b3c 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -80,6 +80,7 @@ from products.surveys.backend.responses import (SurveyRates,SurveyStats,archived_responses_filter,+ build_choice_translation_map,calculate_rates,fetch_per_question_stats,fetch_response_rows,@@ -2874,13 +2875,13 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.# Extract the question text and choices from the surveyquestion_text = None- question_choices = None+ question_dict = Noneif survey.questions and question_id:# Find the question with the matching IDfor idx, question in enumerate(survey.questions):if question.get("id", None) == question_id:question_text = question.get("question")- question_choices = question.get("choices")+ question_dict = question# Backfill the index so the index-based response key fallback works.# Without this, fetch_responses passes question_index=None into the# getSurveyResponse() HogQL function, which requires an integer first@@ -2891,17 +2892,24 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.elif survey.questions and question_index is not None:# Fallback to question index if question_id is not providedif 0 <= question_index < len(survey.questions):- question_text = survey.questions[question_index].get("question")- question_choices = survey.questions[question_index].get("choices")+ question_dict = survey.questions[question_index]+ question_text = question_dict.get("question")if question_text is None:raise exceptions.ValidationError("the text of the question is required")+ # For choice questions, exclude predefined choices (base and translated) to only get+ # open-ended "Other" responses — otherwise a predefined answer given in a non-base+ # language leaks into the free-text set fed to the summarizer. Same translation-aware+ # matching as per_question_stats' distribution.+ exclude_values = None+ if question_dict is not None:+ exclude_values = list(build_choice_translation_map(question_dict).keys()) or None+# Get archived response UUIDs to excludearchived_uuids = get_archived_response_uuids(survey_id, self.team.pk)# Fetch responses using the new module- # For choice questions, exclude predefined choices to only get open-ended "Other" responsesresponses = fetch_responses(survey_id=survey_id,question_index=question_index,@@ -2909,7 +2917,7 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.start_date=(survey.start_date or survey.created_at).replace(hour=0, minute=0, second=0, microsecond=0),end_date=end_date,team=self.team,- exclude_values=question_choices,+ exclude_values=exclude_values,exclude_uuids=archived_uuids,)response_count = len(responses)diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex f86bcaec16ae..51c1ac81399a 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -7119,6 +7119,164 @@ class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):self.assertEqual(per_q[self.open_qid]["response_count"], 3)self.assertEqual(per_q[self.open_qid]["distribution"], {})+ def test_per_question_stats_aggregates_translated_choices(self):+ choice_qid = str(uuid.uuid4())+ survey = Survey.objects.create(+ team=self.team,+ name="Translated",+ type="popover",+ questions=[+ {+ "id": choice_qid,+ "type": "single_choice",+ "question": "Pick one",+ "choices": ["yes", "no"],+ "translations": {"zh-cn": {"choices": ["是", "否"]}},+ },+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )+ for distinct_id, choice in [("u-1", "yes"), ("u-2", "是"), ("u-3", "否")]:+ create_person(team=self.team, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id=distinct_id,+ timestamp="2024-06-10 09:00:00",+ properties={"$survey_id": str(survey.id), f"$survey_response_{choice_qid}": choice},+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{survey.id}/stats/?include_per_question_stats=true"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ per_q = {q["question_id"]: q for q in response.json()["per_question_stats"]}++ # The Chinese "是" answer folds into base "yes"; nothing is redacted into <other>.+ self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 2, "no": 1})+ self.assertEqual(per_q[choice_qid]["response_count"], 3)++ def test_per_question_stats_translation_does_not_remap_base_choice(self):+ choice_qid = str(uuid.uuid4())+ survey = Survey.objects.create(+ team=self.team,+ name="Collision",+ type="popover",+ questions=[+ {+ "id": choice_qid,+ "type": "single_choice",+ "question": "Pick one",+ "choices": ["yes", "no"],+ # Translation reuses base "yes" for the second option; base answers must win.+ "translations": {"fr": {"choices": ["oui", "yes"]}},+ },+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )+ for distinct_id, choice in [("u-1", "yes"), ("u-2", "yes"), ("u-3", "oui")]:+ create_person(team=self.team, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id=distinct_id,+ timestamp="2024-06-10 09:00:00",+ properties={"$survey_id": str(survey.id), f"$survey_response_{choice_qid}": choice},+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{survey.id}/stats/?include_per_question_stats=true"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ per_q = {q["question_id"]: q for q in response.json()["per_question_stats"]}++ # Base "yes" answers (2) plus the French "oui" (1) all land on "yes", not "no".+ self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 3})++ def test_per_question_stats_ignores_translations_with_mismatched_length(self):+ choice_qid = str(uuid.uuid4())+ survey = Survey.objects.create(+ team=self.team,+ name="Desync",+ type="popover",+ questions=[+ {+ "id": choice_qid,+ "type": "single_choice",+ "question": "Pick one",+ "choices": ["yes", "no", "maybe"],+ # A choice was removed from the base without updating the translation, so the+ # arrays no longer align by position. Positional mapping is unsafe — the+ # translated answer must fall into <other>, not be misattributed to a base choice.+ "translations": {"fr": {"choices": ["oui", "non"]}},+ },+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )+ for distinct_id, choice in [("u-1", "yes"), ("u-2", "oui")]:+ create_person(team=self.team, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id=distinct_id,+ timestamp="2024-06-10 09:00:00",+ properties={"$survey_id": str(survey.id), f"$survey_response_{choice_qid}": choice},+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{survey.id}/stats/?include_per_question_stats=true"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ per_q = {q["question_id"]: q for q in response.json()["per_question_stats"]}++ # Base "yes" still matches; the misaligned French "oui" is bucketed as <other> rather than+ # being folded into the wrong base choice.+ self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 1, "<other>": 1})+ self.assertEqual(per_q[choice_qid]["response_count"], 2)++ def test_per_question_stats_translation_needed_placeholder_is_not_folded_into_base_choice(self):+ choice_qid = str(uuid.uuid4())+ survey = Survey.objects.create(+ team=self.team,+ name="Placeholder",+ type="popover",+ questions=[+ {+ "id": choice_qid,+ "type": "single_choice",+ "question": "Pick one",+ "choices": ["yes", "no"],+ # The editor stamped the untranslated placeholder at index 1. A respondent who+ # literally answers with that string must not be folded into "no".+ "translations": {"fr": {"choices": ["oui", "[Translation needed]"]}},+ },+ ],+ start_date=datetime(2024, 5, 1, tzinfo=UTC),+ )+ for distinct_id, choice in [("u-1", "yes"), ("u-2", "oui"), ("u-3", "[Translation needed]")]:+ create_person(team=self.team, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id=distinct_id,+ timestamp="2024-06-10 09:00:00",+ properties={"$survey_id": str(survey.id), f"$survey_response_{choice_qid}": choice},+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{survey.id}/stats/?include_per_question_stats=true"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ per_q = {q["question_id"]: q for q in response.json()["per_question_stats"]}++ # "oui" folds into "yes"; the literal placeholder text is bucketed as <other>, not "no".+ self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 2, "<other>": 1})+ self.assertEqual(per_q[choice_qid]["response_count"], 3)+class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):SURVEY_PAYLOAD = {diff --git a/products/surveys/backend/responses/__init__.py b/products/surveys/backend/responses/__init__.pyindex dedd79d03c81..0b639fc2c290 100644--- a/products/surveys/backend/responses/__init__.py+++ b/products/surveys/backend/responses/__init__.py@@ -1,5 +1,6 @@from products.surveys.backend.responses.fetch_rows import (SurveyResponseRow,+ build_choice_translation_map,fetch_response_rows,resolve_question_metadata,)@@ -23,6 +24,7 @@ __all__ = ["SurveyResponseRow","SurveyStats","archived_responses_filter",+ "build_choice_translation_map","calculate_rates","fetch_per_question_stats","fetch_response_rows",diff --git a/products/surveys/backend/responses/fetch_rows.py b/products/surveys/backend/responses/fetch_rows.pyindex b25f7991e47c..23fc46e22e24 100644--- a/products/surveys/backend/responses/fetch_rows.py+++ b/products/surveys/backend/responses/fetch_rows.py@@ -18,6 +18,10 @@ from posthog.models import Teamfrom products.surveys.backend.models import Survey+# Stamped by the frontend editor into a translation's choices when a spot needs a human+# translation. Must never be treated as real translated content.+TRANSLATION_NEEDED_PLACEHOLDER = "[Translation needed]"+@dataclass(frozen=True)class QuestionAnswer:@@ -38,8 +42,59 @@ class SurveyResponseRow:extra: dict[str, Any] = field(default_factory=dict)+def build_choice_translation_map(question: dict[str, Any]) -> dict[str, str]:+ """Map each translated choice back to its base-language choice, matched by position.++ Mirrors the frontend twin ``buildChoiceTranslationMap`` in+ ``frontend/src/scenes/surveys/surveyTranslationUtils.ts``: base choices are seeded last so+ they win on collision with a translation that reuses another base choice's string.+ """+ base_choices = question.get("choices")+ if not isinstance(base_choices, list):+ return {}+ # An untranslated question still needs its base choices mapped, so a missing/malformed+ # `translations` means "no translated entries", never an early return.+ translations = question.get("translations")+ if not isinstance(translations, dict):+ translations = {}++ mapping: dict[str, str] = {}+ for translation in translations.values():+ if not isinstance(translation, dict):+ continue+ translated_choices = translation.get("choices")+ if not isinstance(translated_choices, list):+ continue+ # The length guard only catches out-of-band edits (API/Max tool) that change array+ # length — the editor path preserves length and stamps the placeholder instead (see the+ # placeholder skip below), which is why that skip is the real guard for that path.+ if len(translated_choices) != len(base_choices):+ continue+ for index, choice in enumerate(translated_choices):+ base_choice = base_choices[index]+ # Skip untranslated placeholders and blanks — they carry no real mapping and would+ # otherwise collapse onto whichever base choice the last language lands on.+ if (+ isinstance(choice, str)+ and choice.strip()+ and choice != TRANSLATION_NEEDED_PLACEHOLDER+ and isinstance(base_choice, str)+ ):+ mapping[choice] = base_choice++ # Seed base choices last so they take precedence: a translation that reuses another+ # base-choice string must not remap that base choice to a different option. The tradeoff is+ # lossy — a translated pick that collides with a different base choice is attributed to that+ # base option — but it's the safe default (base-language data is never misattributed).+ for choice in base_choices:+ if isinstance(choice, str):+ mapping[choice] = choice++ return mapping++def resolve_question_metadata(survey: Survey) -> list[dict[str, Any]]:- """Return survey questions with stable `(id, index, text, type, choices)` shape."""+ """Return survey questions with stable `(id, index, text, type, choices, choice_map)` shape."""questions = survey.questions or []resolved: list[dict[str, Any]] = []for index, question in enumerate(questions):@@ -52,6 +107,7 @@ def resolve_question_metadata(survey: Survey) -> list[dict[str, Any]]:"text": question.get("question") or "","type": question.get("type") or "open","choices": question.get("choices"),+ "choice_map": build_choice_translation_map(question),})return resolveddiff --git a/products/surveys/backend/responses/per_question_stats.py b/products/surveys/backend/responses/per_question_stats.pyindex 3d6309eeacea..65b878105733 100644--- a/products/surveys/backend/responses/per_question_stats.py+++ b/products/surveys/backend/responses/per_question_stats.py@@ -123,11 +123,14 @@ def fetch_per_question_stats(# `hasOpenChoice` "Other: ___" response) and would leak respondent-entered content.# Bucket free-text answers under "<other>" so callers still see how many people picked# "Other" without exposing the text itself. Reading the text requires the responses- # endpoint, which requires `query:read`.- allowed_choices: set[str] | None = None+ # endpoint, which requires `query:read`. Translated answers map back to their base+ # choice so they aggregate with it rather than being redacted into "<other>".+ # `multiple_choice` never actually reaches here today: the grouped query above resolves+ # JSON-array answers to '', filtered out before this point. Kept in the tuple so+ # normalization applies for free if the query is ever extended to array-extract answers.+ choice_map: dict[str, str] | None = Noneif question_type in ("single_choice", "multiple_choice"):- choices = q.get("choices") or []- allowed_choices = set(choices) if choices else set()+ choice_map = q.get("choice_map") or {}distribution: dict[str, int] = {}total_count = 0@@ -140,13 +143,16 @@ def fetch_per_question_stats(if not answer_str:continue- if allowed_choices is not None and answer_str not in allowed_choices:- # Free-text "Other" — keep the count but not the value.- other_count += count_n- total_count += count_n- continue+ if choice_map is not None:+ normalized = choice_map.get(answer_str)+ if normalized is None:+ # Free-text "Other" — keep the count but not the value.+ other_count += count_n+ total_count += count_n+ continue+ answer_str = normalized- distribution[answer_str] = count_n+ distribution[answer_str] = distribution.get(answer_str, 0) + count_ntotal_count += count_nif question_type == "rating":try:diff --git a/products/surveys/backend/responses/test_fetch_rows.py b/products/surveys/backend/responses/test_fetch_rows.pynew file mode 100644index 000000000000..fb10c9f5fe42--- /dev/null+++ b/products/surveys/backend/responses/test_fetch_rows.py@@ -0,0 +1,70 @@+"""Unit tests for the pure helpers in fetch_rows (no ClickHouse needed)."""++from django.test import SimpleTestCase++from parameterized import parameterized++from products.surveys.backend.responses.fetch_rows import build_choice_translation_map+++class TestBuildChoiceTranslationMap(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "maps_each_translation_back_to_its_base_choice",+ {"choices": ["yes", "no"], "translations": {"zh-cn": {"choices": ["是", "否"]}}},+ {"是": "yes", "否": "no", "yes": "yes", "no": "no"},+ ),+ (+ "merges_multiple_languages",+ {+ "choices": ["yes", "no"],+ "translations": {"zh-cn": {"choices": ["是", "否"]}, "fr": {"choices": ["oui", "non"]}},+ },+ {"是": "yes", "否": "no", "oui": "yes", "non": "no", "yes": "yes", "no": "no"},+ ),+ (+ "skips_language_when_length_is_out_of_sync",+ # A choice was removed from the base without updating the translation — positional+ # mapping would misalign, so the language is dropped entirely (base-only fallback).+ {"choices": ["yes", "no", "maybe"], "translations": {"fr": {"choices": ["oui", "non"]}}},+ {"yes": "yes", "no": "no", "maybe": "maybe"},+ ),+ (+ "seeds_base_choices_when_the_question_has_no_translations",+ # By far the common case — an untranslated choice question must still map its own+ # choices, otherwise every answer gets bucketed as <other>.+ {"choices": ["yes", "no"]},+ {"yes": "yes", "no": "no"},+ ),+ (+ "seeds_base_choices_when_translations_is_null",+ {"choices": ["yes", "no"], "translations": None},+ {"yes": "yes", "no": "no"},+ ),+ (+ "ignores_question_without_choices",+ {"question": "open ended", "translations": {"fr": {"question": "ouvert"}}},+ {},+ ),+ (+ "ignores_malformed_translation_entries",+ {"choices": ["yes", "no"], "translations": {"fr": {"choices": ["oui", 5]}}},+ {"oui": "yes", "yes": "yes", "no": "no"},+ ),+ (+ "skips_translation_needed_placeholder",+ # The editor stamps this literal into untranslated slots — it must never become a+ # key, or every language's placeholder collapses onto one arbitrary base choice.+ {"choices": ["yes", "no"], "translations": {"fr": {"choices": ["[Translation needed]", "non"]}}},+ {"non": "no", "yes": "yes", "no": "no"},+ ),+ (+ "skips_empty_and_whitespace_only_translated_choices",+ {"choices": ["yes", "no"], "translations": {"fr": {"choices": ["", " "]}}},+ {"yes": "yes", "no": "no"},+ ),+ ]+ )+ def test_build_choice_translation_map(self, _name, question, expected):+ self.assertEqual(build_choice_translation_map(question), expected)