: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): count survey responses via HogQL instead of raw SQL (#91451)
Sandy Spicer329f1c2c0b39
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex f01a3fe85355..4483cfaee129 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -9,7 +9,7 @@ from uuid import UUIDfrom django.conf import settingsfrom django.core.cache import cachefrom django.db import transaction-from django.db.models import Min, QuerySet+from django.db.models import QuerySetfrom django.http import HttpRequest, HttpResponsefrom django.shortcuts import renderfrom django.utils.text import slugify@@ -43,7 +43,6 @@ from posthog.api.documentation import FeatureFlagFiltersSchemaSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import action-from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.cloud_utils import is_cloudfrom posthog.constants import SURVEY_TARGETING_FLAG_PREFIX, AvailableFeature@@ -81,24 +80,18 @@ from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyRfrom products.surveys.backend.responses import (SurveyRates,SurveyStats,- archived_responses_filter,build_choice_translation_map,calculate_rates,fetch_per_question_stats,fetch_response_rows,+ get_survey_responses_count,get_survey_stats,- partial_responses_filter,process_survey_results,validate_and_parse_dates,)from products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responsesfrom products.surveys.backend.translation import generate_survey_translation-from products.surveys.backend.util import (- SurveyEventName,- SurveyEventProperties,- get_archived_response_uuids,- get_survey_property_string_expr,-)+from products.surveys.backend.util import SurveyEventProperties, get_archived_response_uuidsfrom ee.surveys.summaries.headline_summary import generate_survey_headline@@ -2312,12 +2305,6 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)- def _get_partial_responses_filter(self, base_conditions_sql: builtins.list[str]) -> str:- return partial_responses_filter(base_conditions_sql)-- def _get_archived_responses_filter(self, survey_id: str | None = None) -> tuple[str, dict]:- return archived_responses_filter(survey_id, self.team_id)-@action(methods=["GET"], detail=False, required_scopes=["survey:read"])def responses_count(self, request: request.Request, **kwargs):"""Get response counts for all surveys.@@ -2330,62 +2317,10 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Dictionary mapping survey IDs to response counts"""exclude_archived = request.query_params.get("exclude_archived", "false").lower() == "true"- survey_ids_param = request.query_params.get("survey_ids")-- earliest_survey_start_date = Survey.objects.filter(team__project_id=self.project_id).aggregate(- Min("start_date")- )["start_date__min"]-- if not earliest_survey_start_date:- # If there are no surveys or none have a start date, there can be no responses.- return Response({})-- params = {"team_id": self.team_id, "timestamp": earliest_survey_start_date}- survey_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)-- partial_responses_filter = self._get_partial_responses_filter(- base_conditions_sql=[- "team_id = %(team_id)s",- "timestamp >= %(timestamp)s",- ],- )-- archived_filter = ""- if exclude_archived:- archived_filter_sql, archived_params = self._get_archived_responses_filter()- if archived_filter_sql:- archived_filter = f"AND {archived_filter_sql}"- params.update(archived_params)-- survey_ids_filter = ""- if survey_ids_param:- survey_ids = [sid.strip() for sid in survey_ids_param.split(",") if sid.strip()]- if survey_ids:- survey_ids_filter = f"AND {survey_id_expr} IN %(survey_ids)s"- params["survey_ids"] = survey_ids-- query = f"""- SELECT- {survey_id_expr} as survey_id,- count()- FROM events- WHERE- team_id = %(team_id)s- AND event = '{SurveyEventName.SENT}'- AND timestamp >= %(timestamp)s- AND {partial_responses_filter}- {archived_filter}- {survey_ids_filter}- GROUP BY survey_id- """-- tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)- data = sync_execute(query, params)-- counts = {}- for survey_id, count in data:- counts[survey_id] = count+ survey_ids_param = request.query_params.get("survey_ids") or ""+ survey_ids = [survey_id.strip() for survey_id in survey_ids_param.split(",") if survey_id.strip()]+ counts = get_survey_responses_count(team=self.team, exclude_archived=exclude_archived, survey_ids=survey_ids)return Response(counts)def _validate_and_parse_dates(diff --git a/products/surveys/backend/api/test/__snapshots__/test_survey.ambr b/products/surveys/backend/api/test/__snapshots__/test_survey.ambrindex 9aad38e373dd..6ee12cdd79fb 100644--- a/products/surveys/backend/api/test/__snapshots__/test_survey.ambr+++ b/products/surveys/backend/api/test/__snapshots__/test_survey.ambr@@ -2,69 +2,78 @@# name: TestResponsesCount.test_responses_count'''/* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,+ count() AS `count()`FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-01-21 14:40:09'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-01-21 14:40:09'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,+ (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`+ FROM events+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))GROUP BY survey_id+ LIMIT 50000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestResponsesCount.test_responses_count_only_after_first_survey_started'''/* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,+ count() AS `count()`FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-04-25 14:40:09'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-04-25 14:40:09'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,+ (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`+ FROM events+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))GROUP BY survey_id+ LIMIT 50000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestResponsesCount.test_responses_count_with_partial_responses'''/* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,+ count() AS `count()`FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-06-10 11:00:00'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-06-10 11:00:00'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')), globalIn(events.uuid,+ (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`+ FROM events+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))GROUP BY survey_id+ LIMIT 50000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex a06d09820c9c..072275a07c21 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -21,6 +21,8 @@ from nanoid import generatefrom parameterized import parameterizedfrom rest_framework import status+from posthog.hogql.constants import DEFAULT_RETURNED_ROWS+from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeaturefrom posthog.models import Team@@ -5409,6 +5411,24 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):self.assertEqual(data, expected_counts)+ @freeze_time("2024-05-01 14:40:09")+ def test_responses_count_returns_more_surveys_than_the_hogql_default_limit(self):+ Survey.objects.create(team_id=self.team.id, start_date=datetime.now() - timedelta(days=1))+ survey_ids = [str(uuid.uuid4()) for _ in range(DEFAULT_RETURNED_ROWS + 1)]+ for survey_id in survey_ids:+ _create_event(+ event="survey sent",+ team=self.team,+ distinct_id=self.user.id,+ properties={"$survey_id": survey_id},+ timestamp=datetime.now(),+ )++ response = self.client.get(f"/api/projects/{self.team.id}/surveys/responses_count")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), dict.fromkeys(survey_ids, 1))+@freeze_time("2024-05-01 14:40:09")def test_responses_count_excludes_archived_responses(self):survey_id = str(uuid.uuid4())diff --git a/products/surveys/backend/responses/__init__.py b/products/surveys/backend/responses/__init__.pyindex 0b639fc2c290..cf8e1d5d355a 100644--- a/products/surveys/backend/responses/__init__.py+++ b/products/surveys/backend/responses/__init__.py@@ -9,10 +9,9 @@ from products.surveys.backend.responses.stats import (EventStats,SurveyRates,SurveyStats,- archived_responses_filter,calculate_rates,+ get_survey_responses_count,get_survey_stats,- partial_responses_filter,process_survey_results,validate_and_parse_dates,)@@ -23,13 +22,12 @@ __all__ = ["SurveyRates","SurveyResponseRow","SurveyStats",- "archived_responses_filter","build_choice_translation_map","calculate_rates","fetch_per_question_stats","fetch_response_rows",+ "get_survey_responses_count","get_survey_stats",- "partial_responses_filter","process_survey_results","resolve_question_metadata","validate_and_parse_dates",diff --git a/products/surveys/backend/responses/stats.py b/products/surveys/backend/responses/stats.pyindex fb395cb41895..3aaa118a3a6f 100644--- a/products/surveys/backend/responses/stats.py+++ b/products/surveys/backend/responses/stats.py@@ -3,7 +3,8 @@Single source of truth for the "survey performance" numbers (shown / dismissed / sentcounts, unique persons, and derived response/dismissal rates). Both the surveys RESTviewset and the dashboard survey widget call `get_survey_stats` so there is exactly one-query path for these stats.+query path for these stats. `get_survey_responses_count` shares its definition of a unique+sent response."""from __future__ import annotations@@ -11,20 +12,20 @@ from __future__ import annotationsfrom datetime import UTC, datetimefrom typing import Any, TypedDict+from django.db.models import Min+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode, ProductKeyfrom posthog.hogql import ast+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWSfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.models import Teamfrom products.surveys.backend.models import Survey-from products.surveys.backend.util import (- SurveyEventName,- get_archived_response_uuids,- get_unique_survey_event_uuids_sql_subquery,-)+from products.surveys.backend.responses.fetch_rows import SUBMISSION_GROUPING_KEY+from products.surveys.backend.util import SurveyEventName, get_archived_response_uuidsclass EventStats(TypedDict):@@ -88,24 +89,6 @@ def validate_and_parse_dates(date_from: str | None, date_to: str | None) -> tupl) from exc-def partial_responses_filter(base_conditions_sql: list[str]) -> str:- unique_uuids_subquery = get_unique_survey_event_uuids_sql_subquery(- base_conditions_sql=base_conditions_sql,- )-- return f"uuid IN {unique_uuids_subquery}"---def archived_responses_filter(survey_id: str | None, team_id: int) -> tuple[str, dict]:- archived_uuids = get_archived_response_uuids(survey_id, team_id)-- if not archived_uuids:- return "", {}-- params = {"archived_uuids": list(archived_uuids)}- return "uuid NOT IN %(archived_uuids)s", params--def _isoformat_utc_z(value: datetime | None) -> str | None:if value is None:return None@@ -195,6 +178,24 @@ def calculate_rates(stats: SurveyStats) -> SurveyRates:return rates+def _latest_sent_event_uuids_subquery(scan_conditions: str) -> str:+ """HogQL subquery selecting the uuid of the latest "survey sent" event per submission.++ Multiple partial "survey sent" events can exist per submission; only the latest per+ $survey_submission_id counts, and events without one count by their own uuid (see+ SUBMISSION_GROUPING_KEY). Grouping per $survey_id keeps a submission id scoped to its+ survey. `scan_conditions` must start with " AND " and only narrows the scan window; it+ is deliberately not filtered by survey, so a caller scoped to one survey still dedupes+ against every sent event in the window.+ """+ return f"""(+ SELECT argMax(uuid, timestamp)+ FROM events+ WHERE event = '{SurveyEventName.SENT}'{scan_conditions}+ GROUP BY properties.$survey_id, {SUBMISSION_GROUPING_KEY}+ )"""++def get_survey_stats(*,team_id: int,@@ -278,19 +279,7 @@ def get_survey_stats(condition_sql = "".join(f"\n AND {condition}" for condition in conditions)- # Multiple partial "survey sent" events can exist per submission; only the latest per- # $survey_submission_id counts (pre-submission-id events group by their own uuid). Deliberately- # not filtered by survey, matching get_unique_survey_event_uuids_sql_subquery's semantics.- sent_dedup_sql = f"""(event != {{sent}} OR uuid IN (- SELECT argMax(uuid, timestamp)- FROM events- WHERE event = {{sent}}{date_conditions}- GROUP BY if(- coalesce(properties.$survey_submission_id, '') = '',- toString(uuid),- properties.$survey_submission_id- )- ))"""+ sent_dedup_sql = f"(event != {{sent}} OR uuid IN {_latest_sent_event_uuids_subquery(date_conditions)})"tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)@@ -376,3 +365,54 @@ def get_survey_stats("stats": stats,"rates": rates,}+++def get_survey_responses_count(+ *, team: Team, exclude_archived: bool = False, survey_ids: list[str] | None = None+) -> dict[str, int]:+ """Count unique "survey sent" responses per survey, keyed by survey id.++ Only events since the earliest survey start date in the project are scanned. With no+ started survey there can be no responses, so that case returns empty without a query.+ """+ earliest_start_date = Survey.objects.filter(team__project_id=team.project_id).aggregate(Min("start_date"))[+ "start_date__min"+ ]+ if not earliest_start_date:+ return {}++ placeholders: dict[str, ast.Expr] = {"since": ast.Constant(value=earliest_start_date)}+ conditions = [f"uuid IN {_latest_sent_event_uuids_subquery(' AND timestamp >= {since}')}"]++ if exclude_archived:+ archived_uuids = get_archived_response_uuids(None, team.pk)+ if archived_uuids:+ conditions.append("uuid NOT IN {archived_uuids}")+ placeholders["archived_uuids"] = ast.Constant(value=sorted(archived_uuids))++ if survey_ids:+ conditions.append("properties.$survey_id IN {survey_ids}")+ placeholders["survey_ids"] = ast.Constant(value=survey_ids)++ condition_sql = "".join(f"\n AND {condition}" for condition in conditions)++ # HogQL adds a 100-row LIMIT to a top-level SELECT without one, which would silently drop+ # surveys past the first hundred; MAX_SELECT_RETURNED_ROWS is the most a query may return.+ query = f"""+ SELECT properties.$survey_id AS survey_id, count()+ FROM events+ WHERE event = '{SurveyEventName.SENT}'+ AND timestamp >= {{since}}{condition_sql}+ GROUP BY survey_id+ LIMIT {MAX_SELECT_RETURNED_ROWS}+ """++ tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)+ results = execute_hogql_query(+ query,+ placeholders=placeholders,+ team=team,+ query_type="survey_responses_count",+ ).results++ return dict(results)diff --git a/products/surveys/backend/util.py b/products/surveys/backend/util.pyindex 694bf4b5d5f2..5df7fcea1ef4 100644--- a/products/surveys/backend/util.py+++ b/products/surveys/backend/util.py@@ -43,12 +43,6 @@ def get_survey_property_string_expr(return expression-def get_survey_property_bool_expr(property_name: SurveyEventProperties, table_alias: str | None = None) -> str:- expression = get_survey_property_string_expr(property_name, table_alias)- normalized_expression = f"toString(nullIf(nullIf({expression}, ''), 'null'))"- return f"toBool(transform({normalized_expression}, ['true', 'false'], [1, 0], NULL))"--def get_survey_response_clickhouse_query(question_index: int, question_id: str | None = None, is_multiple_choice: bool = False) -> str: