: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): run survey maintenance task queries through hogql (#69539)
Andy Zhao3a73c7cdd7cc
diff --git a/posthog/tasks/stop_surveys_reached_target.py b/posthog/tasks/stop_surveys_reached_target.pyindex 45a172beb5f1..0731e41e04ca 100644--- a/posthog/tasks/stop_surveys_reached_target.py+++ b/posthog/tasks/stop_surveys_reached_target.py@@ -6,51 +6,48 @@ from django.utils import timezonefrom posthog.schema import ProductKey-from posthog.clickhouse.client import sync_execute+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTfrom products.surveys.backend.models import Survey-from products.surveys.backend.util import SurveyEventProperties, get_survey_property_string_exprdef _get_surveys_response_counts(- surveys_ids: list[UUIDT], team_id: int, earliest_survey_creation_date: datetime+ surveys_ids: list[UUIDT], team: Team, earliest_survey_creation_date: datetime) -> dict[str, int]:- survey_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)- submission_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_SUBMISSION_ID)-tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)- # nosemgrep: clickhouse-fstring-param-audit - survey property expressions come from internal helper output- data = sync_execute(- f"""+ response = execute_hogql_query(+ """SELECT- {survey_id_expr} as survey_id,- count(DISTINCT- if(coalesce({submission_id_expr}, '') != '',- {submission_id_expr},- toString(uuid))- ) as unique_responses+ properties.$survey_id AS survey_id,+ count(DISTINCT if(+ coalesce(properties.$survey_submission_id, '') != '',+ properties.$survey_submission_id,+ toString(uuid)+ )) AS unique_responsesFROM eventsWHERE event = 'survey sent'- AND team_id = %(team_id)s- AND timestamp >= %(earliest_survey_creation_date)s- AND survey_id in %(surveys_ids)s+ AND timestamp >= {earliest_survey_creation_date}+ AND properties.$survey_id IN {surveys_ids}GROUP BY survey_id- """,- {- "surveys_ids": surveys_ids,- "team_id": team_id,- "earliest_survey_creation_date": earliest_survey_creation_date,+ LIMIT {limit}+ """,+ placeholders={+ "earliest_survey_creation_date": ast.Constant(value=earliest_survey_creation_date),+ "surveys_ids": ast.Constant(value=[str(survey_id) for survey_id in surveys_ids]),+ "limit": ast.Constant(value=len(surveys_ids)),},+ team=team,+ query_type="stop_surveys_reached_target",workload=Workload.OFFLINE,)- counts = {}- for survey_id, count in data:- counts[survey_id] = count- return counts+ return dict(response.results)def _stop_survey_if_reached_limit(survey: Survey, responses_count: int) -> None:@@ -74,12 +71,17 @@ def stop_surveys_reached_target() -> None:)all_surveys_sorted = sorted(all_surveys, key=lambda survey: survey.team_id)+ teams_by_id = Team.objects.in_bulk({survey.team_id for survey in all_surveys_sorted})for team_id, team_surveys in groupby(all_surveys_sorted, lambda survey: survey.team_id):+ team = teams_by_id.get(team_id)+ if team is None:+ continue+team_surveys_list = list(team_surveys)surveys_ids = [survey.id for survey in team_surveys_list]earliest_survey_creation_date = min([survey.created_at for survey in team_surveys_list])- response_counts = _get_surveys_response_counts(surveys_ids, team_id, earliest_survey_creation_date)+ response_counts = _get_surveys_response_counts(surveys_ids, team, earliest_survey_creation_date)for survey in team_surveys_list:survey_id = str(survey.id)if survey_id not in response_counts:diff --git a/posthog/tasks/test/__snapshots__/test_stop_surveys_reached_target.ambr b/posthog/tasks/test/__snapshots__/test_stop_surveys_reached_target.ambrindex 4e9bc6b41898..4faa972ec375 100644--- a/posthog/tasks/test/__snapshots__/test_stop_surveys_reached_target.ambr+++ b/posthog/tasks/test/__snapshots__/test_stop_surveys_reached_target.ambr@@ -1,27 +1,43 @@# serializer version: 1# name: TestStopSurveysReachedTarget.test_stop_surveys_with_enough_responses'''-- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count(DISTINCT if(coalesce(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') != '', replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), toString(uuid))) as unique_responses+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,+ count(DISTINCT if(ifNull(notEquals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 1), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), toString(events.uuid))) AS unique_responsesFROM events- WHERE event = 'survey sent'- AND team_id = 99999- AND timestamp >= '2021-12-29 20:00:00'- AND survey_id in ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001' /* ... */]+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2021-12-29 20:00:00.000000', 6, 'UTC')), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), ['00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002']))GROUP BY survey_id+ LIMIT 2 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: TestStopSurveysReachedTarget.test_stop_surveys_with_enough_responses.1'''-- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count(DISTINCT if(coalesce(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') != '', replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), toString(uuid))) as unique_responses+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,+ count(DISTINCT if(ifNull(notEquals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 1), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), toString(events.uuid))) AS unique_responsesFROM events- WHERE event = 'survey sent'- AND team_id = 99999- AND timestamp >= '2022-01-01 00:00:00'- AND survey_id in ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001' /* ... */]+ WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), ['00000000-0000-0000-0000-000000000003']))GROUP BY survey_id+ LIMIT 1 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/posthog/tasks/test/test_stop_surveys_reached_target.py b/posthog/tasks/test/test_stop_surveys_reached_target.pyindex bbf5bede9fdf..703beff7d0ff 100644--- a/posthog/tasks/test/test_stop_surveys_reached_target.py+++ b/posthog/tasks/test/test_stop_surveys_reached_target.py@@ -1,5 +1,6 @@from datetime import datetime, timedeltafrom typing import Optional+from uuid import UUIDfrom freezegun import freeze_timefrom posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events, snapshot_clickhouse_queries@@ -55,8 +56,11 @@ class TestStopSurveysReachedTarget(TestCase, ClickhouseTestMixin):@freeze_time("2022-01-01")@snapshot_clickhouse_queriesdef test_stop_surveys_with_enough_responses(self) -> None:+ # Fixed ids: the survey id list is inlined into the snapshotted ClickHouse SQL,+ # so random ids would make the snapshot depend on test execution order.surveys = [Survey.objects.create(+ id=UUID("00000000-0000-0000-0000-000000000001"),name="1",team=self.team1,created_by=self.user,@@ -64,6 +68,7 @@ class TestStopSurveysReachedTarget(TestCase, ClickhouseTestMixin):responses_limit=1,),Survey.objects.create(+ id=UUID("00000000-0000-0000-0000-000000000002"),name="2",team=self.team1,created_by=self.user,@@ -71,6 +76,7 @@ class TestStopSurveysReachedTarget(TestCase, ClickhouseTestMixin):responses_limit=1,),Survey.objects.create(+ id=UUID("00000000-0000-0000-0000-000000000003"),name="3",team=self.team2,created_by=self.user,diff --git a/posthog/tasks/test/test_update_survey_adaptive_sampling.py b/posthog/tasks/test/test_update_survey_adaptive_sampling.pyindex b344f849a8ba..c1ef18a7b636 100644--- a/posthog/tasks/test/test_update_survey_adaptive_sampling.py+++ b/posthog/tasks/test/test_update_survey_adaptive_sampling.py@@ -42,7 +42,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 20)- mock_get_count.assert_called_once_with(self.survey.id)+ mock_get_count.assert_called_once_with(self.survey)@freeze_time("2024-12-21T12:00:00Z")@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")@@ -51,7 +51,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):update_survey_adaptive_sampling()internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 100)- mock_get_count.assert_called_once_with(self.survey.id)+ mock_get_count.assert_called_once_with(self.survey)survey = Survey.objects.get(id=self.survey.id)assert survey.response_sampling_daily_limits is not Noneresponse_sampling_daily_limits = json.loads(survey.response_sampling_daily_limits)@@ -65,7 +65,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 100)- mock_get_count.assert_called_once_with(self.survey.id)+ mock_get_count.assert_called_once_with(self.survey)@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")def test_ignores_ended_surveys(self, mock_get_count: MagicMock) -> None:diff --git a/posthog/tasks/update_survey_adaptive_sampling.py b/posthog/tasks/update_survey_adaptive_sampling.pyindex b4bf820efbda..03b4b932b938 100644--- a/posthog/tasks/update_survey_adaptive_sampling.py+++ b/posthog/tasks/update_survey_adaptive_sampling.py@@ -3,10 +3,10 @@ from datetime import datetime, timedeltafrom django.utils.timezone import now-from posthog.clickhouse.client import sync_execute+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_queryfrom products.surveys.backend.models import Survey-from products.surveys.backend.util import SurveyEventProperties, get_survey_property_string_exprdef _update_survey_adaptive_sampling(survey: Survey) -> None:@@ -25,7 +25,7 @@ def _update_survey_adaptive_sampling(survey: Survey) -> None:if today_entry is None:return- total_response_count = _get_survey_responses_count(survey.id)+ total_response_count = _get_survey_responses_count(survey)if total_response_count < today_entry.get("daily_response_limit", 0) and survey.internal_response_sampling_flag:# Update the internal_response_sampling_flag's rollout percentageinternal_response_sampling_flag = survey.internal_response_sampling_flag@@ -41,30 +41,25 @@ def _update_survey_adaptive_sampling(survey: Survey) -> None:survey.save(update_fields=["response_sampling_start_date", "response_sampling_daily_limits"])-def _get_survey_responses_count(survey_id: int) -> int:- survey_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)-- # nosemgrep: clickhouse-fstring-param-audit - no interpolation, only parameterized values- data = sync_execute(- f"""- SELECT {survey_id_expr} as survey_id, count()- FROM events- WHERE event = 'survey sent' AND {survey_id_expr} = %(survey_id)s- """,- {"survey_id": survey_id},+def _get_survey_responses_count(survey: Survey) -> int:+ response = execute_hogql_query(+ """+ SELECT count()+ FROM events+ WHERE event = 'survey sent'+ AND properties.$survey_id = {survey_id}+ """,+ placeholders={"survey_id": ast.Constant(value=str(survey.id))},+ team=survey.team,+ query_type="update_survey_adaptive_sampling",)-- counts = {}- for survey_id, count in data:- counts[survey_id] = count-- return counts[survey_id]+ return response.results[0][0] if response.results else 0def update_survey_adaptive_sampling() -> None:surveys_with_adaptive_sampling = Survey.objects.filter(start_date__isnull=False, end_date__isnull=True, response_sampling_daily_limits__isnull=False- ).only("id", "response_sampling_daily_limits")+ ).only("id", "team_id", "response_sampling_daily_limits")for survey in list(surveys_with_adaptive_sampling):_update_survey_adaptive_sampling(survey)diff --git a/products/surveys/backend/util.py b/products/surveys/backend/util.pyindex 96bba60a8e54..519fbdb11936 100644--- a/products/surveys/backend/util.py+++ b/products/surveys/backend/util.py@@ -94,52 +94,6 @@ def _build_multiple_choice_query(_DANGEROUS_id_based_key: str, index_based_key:)"""-def filter_survey_sent_events_by_unique_submission(survey_id: str, team_id: int | None = None) -> str:- """- Generates a SQL condition string to filter 'survey sent' events, ensuring uniqueness based on submission ID,- using an optimized approach with argMax().-- This handles two scenarios for identifying relevant 'survey sent' events:- 1. Events recorded before the introduction of `$survey_submission_id` (submission_id is empty/null):- All such events are considered unique and will be selected (as they form their own group).- 2. Events with `$survey_submission_id`:- Only the single latest event (by timestamp) for each unique `$survey_submission_id` is selected.-- Args:- survey_id: The ID of the survey to filter events for.- team_id: Optional team ID to filter events-- Returns:- A SQL condition string (part of a WHERE clause) filtering event UUIDs.- Example: "uuid IN (SELECT argMax(uuid, timestamp) FROM ... GROUP BY ...)"- """- # Define the column for submission ID to avoid repetition and enhance readability- submission_id_col = get_survey_property_string_expr(SurveyEventProperties.SURVEY_SUBMISSION_ID)-- # Define the grouping key expression. This determines how events are grouped for deduplication.- # If $survey_submission_id is present, group by it. Otherwise, group by uuid (making each old event unique).- grouping_key_expr = (- f"CASE WHEN COALESCE({submission_id_col}, '') = '' THEN toString(uuid) ELSE {submission_id_col} END"- )-- extra_filters = ""- if team_id is not None:- extra_filters += f" AND team_id = {team_id}"-- query = f"""uuid IN (- SELECT- argMax(uuid, timestamp) -- Selects the UUID of the event with the latest timestamp within each group- FROM events- WHERE event = '{SurveyEventName.SENT}' -- Filter for 'survey sent' events- AND {get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)} = {escape_clickhouse_string(survey_id)} -- Filter for the specific survey- {extra_filters}- -- Callers that need bounded deduplication should add the same timestamp filters- -- to the outer query and this subquery.- GROUP BY {grouping_key_expr} -- Group events by the effective submission identifier- )"""- return query--def get_unique_survey_event_uuids_sql_subquery(base_conditions_sql: list[str],group_by_prefix_expressions: list[str] | None = None,