: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): merge survey answers across a submission's events (backend) (#76119)
Phill865d704530b1
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 93242c12b6f8..d2304de47950 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -6884,6 +6884,83 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(data["results"]), 1)self.assertEqual(data["results"][0]["distinct_id"], "new")+ def test_merges_answers_split_across_submission_events(self):+ """A submission split across events — rating on one, free text on another, neither+ repeating the other's answer — should surface as one row carrying both answers."""+ create_person(team=self.team, distinct_ids=["split"])+ submission_id = str(uuid.uuid4())+ # Event 1 (not completed): rating only.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split",+ timestamp="2024-06-10 09:05:00",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.question_id_rating}": "3",+ "$survey_completed": "false",+ },+ )+ # Event 2 (completed): free text only — the rating is NOT repeated here.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split",+ timestamp="2024-06-10 09:05:30",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.question_id_text}": "Because reasons",+ "$survey_completed": "true",+ },+ )+ flush_persons_and_events()++ response = self.client.get(self.url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ # One merged submission, carrying both answers.+ self.assertEqual(len(data["results"]), 1)+ answers_by_id = {a["question_id"]: a["answer"] for a in data["results"][0]["answers"]}+ self.assertEqual(answers_by_id[self.question_id_rating], "3")+ self.assertEqual(answers_by_id[self.question_id_text], "Because reasons")++ def test_score_filter_uses_merged_rating(self):+ """score_lte should match on the merged rating even when it lives on a non-final event."""+ create_person(team=self.team, distinct_ids=["split"])+ submission_id = str(uuid.uuid4())+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split",+ timestamp="2024-06-10 09:05:00",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.question_id_rating}": "2",+ "$survey_completed": "false",+ },+ )+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split",+ timestamp="2024-06-10 09:05:30",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.question_id_text}": "Frustrating",+ "$survey_completed": "true",+ },+ )+ flush_persons_and_events()++ response = self.client.get(self.url, {"question_id": self.question_id_rating, "score_lte": "6"})+ data = response.json()+ self.assertEqual(len(data["results"]), 1)+ self.assertEqual(data["results"][0]["answers"][0]["answer"], "2")+def test_exclude_archived(self):create_person(team=self.team, distinct_ids=["kept"])create_person(team=self.team, distinct_ids=["archived"])@@ -7305,6 +7382,53 @@ class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 2, "<other>": 1})self.assertEqual(per_q[choice_qid]["response_count"], 3)+ def test_per_question_stats_merges_answers_across_submission_events(self):+ """Answers split across a submission's events should all count toward per-question stats,+ even when the completed event only carries one of them."""+ create_person(team=self.team, distinct_ids=["split-user"])+ submission_id = str(uuid.uuid4())+ # Event 1 (not completed): rating + choice only.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split-user",+ timestamp="2024-06-10 09:00:00",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.rating_qid}": "9",+ f"$survey_response_{self.choice_qid}": "yes",+ "$survey_completed": "false",+ },+ )+ # Event 2 (completed): open text only — rating/choice are NOT repeated here.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="split-user",+ timestamp="2024-06-10 09:01:00",+ properties={+ "$survey_id": str(self.survey.id),+ "$survey_submission_id": submission_id,+ f"$survey_response_{self.open_qid}": "Nice",+ "$survey_completed": "true",+ },+ )+ flush_persons_and_events()++ response = self.client.get(+ f"/api/projects/{self.team.id}/surveys/{self.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"]}++ # All three answers count for the single submission, despite living on different events.+ self.assertEqual(per_q[self.rating_qid]["response_count"], 1)+ self.assertEqual(per_q[self.rating_qid]["distribution"], {"9": 1})+ self.assertEqual(per_q[self.choice_qid]["response_count"], 1)+ self.assertEqual(per_q[self.choice_qid]["distribution"], {"yes": 1})+ self.assertEqual(per_q[self.open_qid]["response_count"], 1)+class TestSurveyFeatureFlagScopeWarning(PersonalAPIKeysBaseTest, APIBaseTest):SURVEY_PAYLOAD = {diff --git a/products/surveys/backend/responses/fetch_rows.py b/products/surveys/backend/responses/fetch_rows.pyindex 23fc46e22e24..d7165db7ab93 100644--- a/products/surveys/backend/responses/fetch_rows.py+++ b/products/surveys/backend/responses/fetch_rows.py@@ -11,7 +11,7 @@ from datetime import UTC, datetimefrom typing import Any, castfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.models import Team@@ -113,6 +113,15 @@ def resolve_question_metadata(survey: Survey) -> list[dict[str, Any]]:return resolved+# HogQL expression that collapses a submission's events into one group. Events without a+# `$survey_submission_id` are keyed by their own uuid, so each stays a distinct response+# (the legacy single-event behavior). Shared with the summarization + per-question-stats+# fetchers so the grouping stays identical across every response surface.+SUBMISSION_GROUPING_KEY = (+ "if(coalesce(properties.$survey_submission_id, '') = '', toString(uuid), properties.$survey_submission_id)"+)++# Metadata columns appended to every row — known $-prefixed event properties resolved via# HogQL property accessors (backticked because the keys are literal property names, not# placeholder values).@@ -161,74 +170,98 @@ def fetch_response_rows(placeholders: dict[str, ast.Expr] = {"survey_id": ast.Constant(value=survey_id),- # uniqueSurveySubmissionsFilter requires bounded dates — fall back to- # the survey lifetime when the caller didn't supply explicit bounds.+ # The submission-merge query is bounded by date — fall back to the survey+ # lifetime when the caller didn't supply explicit bounds."start_date": ast.Constant(value=since or survey.start_date or survey.created_at),"end_date": ast.Constant(value=until or survey.end_date or datetime.now(UTC)),}- # Dynamically add one column per question using the HogQL getSurveyResponse helper —- # the same helper the summarization fetch uses, so the resolution semantics match.- answer_columns: list[str] = []+ # Resolve one answer column per question with the HogQL getSurveyResponse helper (the+ # same helper the summarization fetch uses, so resolution semantics match), then merge+ # them across the submission: for each $survey_submission_id we keep the latest non-null+ # answer to each question. This stops multi-event submissions — e.g. AI-feedback manual+ # capture, where each answer can arrive on its own event — from dropping answers that+ # only ever appeared on a non-final event.+ inner_answer_columns: list[str] = []+ outer_answer_columns: list[str] = []for q in questions_in_scope:idx_name = f"q_idx_{q['index']}"id_name = f"q_id_{q['index']}"- answer_columns.append(f"getSurveyResponse({{{idx_name}}}, {{{id_name}}}) AS answer_{q['index']}")+ inner_answer_columns.append(f"getSurveyResponse({{{idx_name}}}, {{{id_name}}}) AS raw_answer_{q['index']}")+ outer_answer_columns.append(+ f"argMaxIf(raw_answer_{q['index']}, timestamp, isNotNull(raw_answer_{q['index']})) AS answer_{q['index']}"+ )placeholders[idx_name] = ast.Constant(value=q["index"])placeholders[id_name] = ast.Constant(value=q["id"])- select_clause = ", ".join(+ placeholders["grouping_key"] = parse_expr(SUBMISSION_GROUPING_KEY)++ # Per-event projection (inner) → per-submission merge (outer). Column order in the outer+ # SELECT must stay uuid, distinct_id, submitted_at, <metadata…>, <answers…> to match the+ # positional parsing below.+ inner_select = ", ".join(["uuid","distinct_id",- "timestamp AS submitted_at",+ "timestamp",*(f"{expr} AS {alias}" for alias, expr in _METADATA_COLUMNS),- *answer_columns,+ *inner_answer_columns,+ "{grouping_key} AS submission_key",+ ]+ )+ outer_select = ", ".join(+ [+ "argMax(uuid, timestamp) AS uuid",+ "argMax(distinct_id, timestamp) AS distinct_id",+ "max(timestamp) AS submitted_at",+ *(f"argMax({alias}, timestamp) AS {alias}" for alias, _ in _METADATA_COLUMNS),+ *outer_answer_columns,])- conditions = [+ inner_conditions = ["event = 'survey sent'","properties.`$survey_id` = {survey_id}",- "uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})",+ "timestamp >= {start_date}",+ "timestamp <= {end_date}",]- if since is not None:- conditions.append("timestamp >= {since}")- placeholders["since"] = ast.Constant(value=since)- if until is not None:- conditions.append("timestamp <= {until}")- placeholders["until"] = ast.Constant(value=until)-+ # Filters that depend on the merged answer run in HAVING, after the submission has been+ # collapsed to a single row.+ having_conditions: list[str] = []if question_id:- # Only return rows where this question has a non-empty answer.+ # Only return submissions where this question has a non-empty answer.# coalesce-then-trim defends against NULL semantics in HogQL — without it the# equivalent `trim(...) != ''` predicate evaluates to NULL for nullified responses# and is silently ignored in some contexts.target_q = next(q for q in questions_in_scope if q["id"] == question_id)- conditions.append(- "length(trim(coalesce(getSurveyResponse({filter_q_idx}, {filter_q_id}), ''))) > 0",- )- placeholders["filter_q_idx"] = ast.Constant(value=target_q["index"])- placeholders["filter_q_id"] = ast.Constant(value=target_q["id"])+ having_conditions.append(f"length(trim(coalesce(answer_{target_q['index']}, ''))) > 0")if score_lte is not None:- conditions.append("toFloat(getSurveyResponse({filter_q_idx}, {filter_q_id})) <= {score_lte}")+ having_conditions.append(f"toFloat(answer_{target_q['index']}) <= {{score_lte}}")placeholders["score_lte"] = ast.Constant(value=score_lte)if score_gte is not None:- conditions.append("toFloat(getSurveyResponse({filter_q_idx}, {filter_q_id})) >= {score_gte}")+ having_conditions.append(f"toFloat(answer_{target_q['index']}) >= {{score_gte}}")placeholders["score_gte"] = ast.Constant(value=score_gte)if exclude_uuids:- conditions.append("uuid NOT IN {exclude_uuids}")+ # Archiving records the submission's representative (latest) uuid, which is exactly+ # what argMax(uuid) surfaces here — so exclude by that.+ having_conditions.append("uuid NOT IN {exclude_uuids}")placeholders["exclude_uuids"] = ast.Tuple(exprs=[ast.Constant(value=u) for u in exclude_uuids])- query_str = f"""- SELECT {select_clause}- FROM events- WHERE {" AND ".join(conditions)}- ORDER BY timestamp DESC- """+ having_clause = ("HAVING " + " AND ".join(having_conditions)) if having_conditions else ""+ query_str = (+ "SELECT "+ + outer_select+ + " FROM ( SELECT "+ + inner_select+ + " FROM events WHERE "+ + " AND ".join(inner_conditions)+ + " ) GROUP BY submission_key "+ + having_clause+ + " ORDER BY submitted_at DESC"+ )select_ast = cast(ast.SelectQuery, parse_select(query_str, placeholders))paginator.execute_hogql_query(diff --git a/products/surveys/backend/responses/per_question_stats.py b/products/surveys/backend/responses/per_question_stats.pyindex 65b878105733..21489128d6b7 100644--- a/products/surveys/backend/responses/per_question_stats.py+++ b/products/surveys/backend/responses/per_question_stats.py@@ -5,13 +5,13 @@ from datetime import UTC, datetimefrom typing import castfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.models import Teamfrom products.surveys.backend.models import Survey-from products.surveys.backend.responses.fetch_rows import resolve_question_metadata+from products.surveys.backend.responses.fetch_rows import SUBMISSION_GROUPING_KEY, resolve_question_metadata@dataclass(frozen=True)@@ -60,6 +60,7 @@ def fetch_per_question_stats("end_date": ast.Constant(value=end_date),"q_idx": ast.Constant(value=question_index),"q_id": ast.Constant(value=question_id),+ "grouping_key": parse_expr(SUBMISSION_GROUPING_KEY),}# For open questions: just count non-empty responses — distribution across free-text@@ -69,14 +70,25 @@ def fetch_per_question_stats(# resolves to NULL (e.g. via its nullIf path) — `NULL != ''` is NULL, which would# filter the row implicitly but doesn't always behave consistently in count contexts.if question_type == "open":+ # Merge each submission's events into one answer (latest non-null), then count+ # the submissions that ended up with a non-empty answer.query_str = """- SELECT countIf(length(trim(coalesce(getSurveyResponse({q_idx}, {q_id}), ''))) > 0) AS n- FROM events- WHERE event = 'survey sent'- AND properties.`$survey_id` = {survey_id}- AND timestamp >= {start_date}- AND timestamp <= {end_date}- AND uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})+ SELECT countIf(length(trim(coalesce(answer, ''))) > 0) AS n+ FROM (+ SELECT argMaxIf(response, timestamp, isNotNull(response)) AS answer+ FROM (+ SELECT+ getSurveyResponse({q_idx}, {q_id}) AS response,+ timestamp,+ {grouping_key} AS submission_key+ FROM events+ WHERE event = 'survey sent'+ AND properties.`$survey_id` = {survey_id}+ AND timestamp >= {start_date}+ AND timestamp <= {end_date}+ )+ GROUP BY submission_key+ )"""select_ast = cast(ast.SelectQuery, parse_select(query_str, placeholders))response = execute_hogql_query(@@ -98,15 +110,26 @@ def fetch_per_question_stats(# For rating/choice: aggregate by answer value to get a distribution.# Same defensive coalesce as the open branch — filter out NULL and empty before grouping.+ # Merge each submission's events into one answer (latest non-null), then build the+ # distribution across those merged answers.query_str = """- SELECT getSurveyResponse({q_idx}, {q_id}) AS answer, count() AS n- FROM events- WHERE event = 'survey sent'- AND properties.`$survey_id` = {survey_id}- AND timestamp >= {start_date}- AND timestamp <= {end_date}- AND uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})- AND length(trim(coalesce(getSurveyResponse({q_idx}, {q_id}), ''))) > 0+ SELECT answer, count() AS n+ FROM (+ SELECT argMaxIf(response, timestamp, isNotNull(response)) AS answer+ FROM (+ SELECT+ getSurveyResponse({q_idx}, {q_id}) AS response,+ timestamp,+ {grouping_key} AS submission_key+ FROM events+ WHERE event = 'survey sent'+ AND properties.`$survey_id` = {survey_id}+ AND timestamp >= {start_date}+ AND timestamp <= {end_date}+ )+ GROUP BY submission_key+ HAVING length(trim(coalesce(answer, ''))) > 0+ )GROUP BY answerORDER BY n DESCLIMIT 200diff --git a/products/surveys/backend/summarization/fetch.py b/products/surveys/backend/summarization/fetch.pyindex 46d6134bb863..53709c91e446 100644--- a/products/surveys/backend/summarization/fetch.py+++ b/products/surveys/backend/summarization/fetch.py@@ -4,11 +4,13 @@ from datetime import datetimefrom typing import castfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.models import Team+from products.surveys.backend.responses.fetch_rows import SUBMISSION_GROUPING_KEY+def fetch_responses(survey_id: str,@@ -40,24 +42,39 @@ def fetch_responses("""paginator = HogQLHasMorePaginator(limit=limit, offset=0)- # Build the base query- # Use uniqueSurveySubmissionsFilter to deduplicate by $survey_submission_id- # This ensures multiple "survey sent" events for the same submission are rolled up+ # Merge a submission's events instead of picking a single one: for each+ # $survey_submission_id, keep the latest non-null answer to this question. This stops+ # multi-event submissions (e.g. AI-feedback manual capture, where each answer can arrive+ # on its own event) from dropping answers that only appeared on a non-final event.+ # Events without a submission ID are keyed by uuid, so each stays its own response.base_query = """- SELECT getSurveyResponse({question_index}, {question_id})- FROM events- WHERE event == 'survey sent'- AND timestamp >= {start_date}- AND timestamp <= {end_date}- AND properties.`$survey_id` = {survey_id}- AND uniqueSurveySubmissionsFilter({survey_id}, {start_date}, {end_date})- AND trim(getSurveyResponse({question_index}, {question_id})) != ''+ SELECT merged_response+ FROM (+ SELECT+ argMaxIf(response, timestamp, isNotNull(response)) AS merged_response,+ argMax(uuid, timestamp) AS representative_uuid+ FROM (+ SELECT+ getSurveyResponse({question_index}, {question_id}) AS response,+ timestamp,+ uuid,+ {grouping_key} AS submission_key+ FROM events+ WHERE event == 'survey sent'+ AND timestamp >= {start_date}+ AND timestamp <= {end_date}+ AND properties.`$survey_id` = {survey_id}+ )+ GROUP BY submission_key+ )+ WHERE length(trim(coalesce(merged_response, ''))) > 0"""- # Add archived response filter if there are UUIDs to exclude+ # Add archived response filter if there are UUIDs to exclude. Archiving records the+ # submission's representative (latest) uuid, which is what argMax(uuid) surfaces above.# UUIDs are pre-validated by Django's UUIDField when stored in SurveyResponseArchiveif exclude_uuids:- base_query += " AND uuid NOT IN {exclude_uuids}"+ base_query += " AND representative_uuid NOT IN {exclude_uuids}"placeholders: dict[str, ast.Expr] = {"survey_id": ast.Constant(value=survey_id),@@ -65,6 +82,7 @@ def fetch_responses("end_date": ast.Constant(value=end_date),"question_index": ast.Constant(value=question_index),"question_id": ast.Constant(value=question_id),+ "grouping_key": parse_expr(SUBMISSION_GROUPING_KEY),}if exclude_uuids:diff --git a/products/surveys/backend/summarization/test_fetch.py b/products/surveys/backend/summarization/test_fetch.pyindex a6c59e880b5c..c56e5e59591b 100644--- a/products/surveys/backend/summarization/test_fetch.py+++ b/products/surveys/backend/summarization/test_fetch.py@@ -220,3 +220,112 @@ class TestFetchResponses(ClickhouseTestMixin, APIBaseTest):# Only the valid response should be returnedassert len(responses) == 1assert responses[0] == "Valid response"++ def test_merges_answer_from_earlier_event_in_submission(self):+ """A question answered on an earlier event should survive even when the latest event+ in the submission doesn't repeat it (non-cumulative multi-event capture)."""+ survey_id = str(uuid.uuid4())+ submission_id = str(uuid.uuid4())+ q_rating = str(uuid.uuid4())+ q_text = str(uuid.uuid4())++ # Event 1 (not completed): answers the rating question only.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="user1",+ timestamp=datetime.now() - timedelta(hours=2),+ properties={+ "$survey_id": survey_id,+ "$survey_submission_id": submission_id,+ f"$survey_response_{q_rating}": "8",+ "$survey_completed": "false",+ },+ )+ # Event 2 (completed): answers the free-text question only — the rating is NOT repeated.+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="user1",+ timestamp=datetime.now() - timedelta(hours=1),+ properties={+ "$survey_id": survey_id,+ "$survey_submission_id": submission_id,+ f"$survey_response_{q_text}": "Great product",+ "$survey_completed": "true",+ },+ )++ flush_persons_and_events()++ # The rating lives only on the earlier event, but must still be returned.+ rating_responses = fetch_responses(+ survey_id=survey_id,+ question_index=0,+ question_id=q_rating,+ start_date=datetime.now() - timedelta(days=1),+ end_date=datetime.now(),+ team=self.team,+ )+ assert rating_responses == ["8"]++ # The free-text answer lives only on the later event.+ text_responses = fetch_responses(+ survey_id=survey_id,+ question_index=1,+ question_id=q_text,+ start_date=datetime.now() - timedelta(days=1),+ end_date=datetime.now(),+ team=self.team,+ )+ assert text_responses == ["Great product"]++ def test_latest_non_null_wins_for_same_question(self):+ """When the same question is answered on multiple events, the latest non-null value wins,+ and a later null does not blank out an earlier answer."""+ survey_id = str(uuid.uuid4())+ submission_id = str(uuid.uuid4())+ q_id = str(uuid.uuid4())++ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="user1",+ timestamp=datetime.now() - timedelta(hours=3),+ properties={+ "$survey_id": survey_id,+ "$survey_submission_id": submission_id,+ f"$survey_response_{q_id}": "first",+ },+ )+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="user1",+ timestamp=datetime.now() - timedelta(hours=2),+ properties={+ "$survey_id": survey_id,+ "$survey_submission_id": submission_id,+ f"$survey_response_{q_id}": "second",+ },+ )+ # Latest event answers a *different* question, leaving this one null — must not blank "second".+ _create_event(+ team=self.team,+ event="survey sent",+ distinct_id="user1",+ timestamp=datetime.now() - timedelta(hours=1),+ properties={"$survey_id": survey_id, "$survey_submission_id": submission_id, "$survey_response_other": "x"},+ )++ flush_persons_and_events()++ responses = fetch_responses(+ survey_id=survey_id,+ question_index=0,+ question_id=q_id,+ start_date=datetime.now() - timedelta(days=1),+ end_date=datetime.now(),+ team=self.team,+ )+ assert responses == ["second"]