: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): end repeating surveys after their final iteration (#68735)
Lucas Fariaa0c9b84f223a
diff --git a/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx b/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsxindex cd83c3e1293c..b62df71da165 100644--- a/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx+++ b/frontend/src/scenes/surveys/SurveyRepeatSchedule.tsx@@ -176,7 +176,7 @@ function SurveyIterationOptions(): JSX.Element {<div className="text-xs text-muted">{survey.iteration_count === 1? 'This survey will only be shown once (no repeats).'- : `This survey will be shown now, then ${survey.iteration_count - 1} more ${pluralize(survey.iteration_count - 1, 'time', 'times', false)} with ${pluralize(survey.iteration_frequency_days, 'day')} between each.`}+ : `This survey runs for ${survey.iteration_count} iterations of ${pluralize(survey.iteration_frequency_days, 'day')} each, counted from the launch date. Each user can respond once per iteration.`}</div>)}</div>diff --git a/frontend/src/scenes/surveys/wizard/steps/SuccessStep.test.tsx b/frontend/src/scenes/surveys/wizard/steps/SuccessStep.test.tsxindex 33fa2b1b5895..1d8e0ee97c52 100644--- a/frontend/src/scenes/surveys/wizard/steps/SuccessStep.test.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/SuccessStep.test.tsx@@ -56,6 +56,6 @@ describe('SuccessStep', () => {/>)- expect(screen.getByText('Up to 2 times, every 90 days')).toBeInTheDocument()+ expect(screen.getByText('Up to 2 times, every 90 days from launch')).toBeInTheDocument()})})diff --git a/frontend/src/scenes/surveys/wizard/steps/SuccessStep.tsx b/frontend/src/scenes/surveys/wizard/steps/SuccessStep.tsxindex ac6331e46b25..575562591e8e 100644--- a/frontend/src/scenes/surveys/wizard/steps/SuccessStep.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/SuccessStep.tsx@@ -94,7 +94,7 @@ export function SuccessStep({ survey }: SuccessStepProps): JSX.Element {? 'Every time a trigger event is captured': survey.schedule === SurveySchedule.Once || !survey.iteration_frequency_days? 'Once ever'- : `Up to ${survey.iteration_count ?? 10} times, every ${survey.iteration_frequency_days} days`}+ : `Up to ${survey.iteration_count ?? 10} times, every ${survey.iteration_frequency_days} days from launch`}</dd></div>{survey.conditions?.seenSurveyWaitPeriodInDays != null && (diff --git a/frontend/src/scenes/surveys/wizard/steps/WhenStep.test.tsx b/frontend/src/scenes/surveys/wizard/steps/WhenStep.test.tsxindex 0433b09aa3c7..f2fe6ac258b2 100644--- a/frontend/src/scenes/surveys/wizard/steps/WhenStep.test.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/WhenStep.test.tsx@@ -96,4 +96,20 @@ describe('WhenStep', () => {expect(screen.getByText('Once ever')).toBeInTheDocument()expect(screen.queryByText(/the schedule options don't apply/)).not.toBeInTheDocument()})++ it('surfaces a non-preset recurring cadence as a custom option instead of falling back to once', async () => {+ useMocks(+ surveyMocks({+ ...createEventTriggeredSurvey(false),+ conditions: { actions: null, events: null },+ schedule: SurveySchedule.Recurring,+ iteration_count: 5,+ iteration_frequency_days: 45,+ })+ )+ renderWhenStep()++ expect(await screen.findByText('Every 45 days')).toBeInTheDocument()+ expect(screen.getByText(/times in total/)).toBeInTheDocument()+ })})diff --git a/frontend/src/scenes/surveys/wizard/steps/WhenStep.tsx b/frontend/src/scenes/surveys/wizard/steps/WhenStep.tsxindex e604e7a1fc40..236c50158cf6 100644--- a/frontend/src/scenes/surveys/wizard/steps/WhenStep.tsx+++ b/frontend/src/scenes/surveys/wizard/steps/WhenStep.tsx@@ -59,12 +59,25 @@ export function WhenStep(): JSX.Element {const delaySeconds = appearance.surveyPopupDelaySeconds ?? 0const excludedObjectProperties = useExcludedObjectProperties()// Derive frequency strictly from the iteration model — the universal wait-period is a separate- // across-surveys gate and must not influence which cadence is highlighted. Default to 'once' so- // an unconfigured survey doesn't silently imply a recurring cadence.+ // across-surveys gate and must not influence which cadence is highlighted.+ const presetFrequency = FREQUENCY_OPTIONS.find((opt) => opt.days === survey.iteration_frequency_days)?.value+ // A recurring survey with a non-preset cadence (set in the full editor) must not render as+ // 'Once ever' — surface it as a custom option instead.const frequency =- survey.schedule === SurveySchedule.Once+ survey.schedule === SurveySchedule.Once || !survey.iteration_frequency_days? 'once'- : (FREQUENCY_OPTIONS.find((opt) => opt.days === survey.iteration_frequency_days)?.value ?? 'once')+ : (presetFrequency ?? 'custom')+ const frequencyOptions =+ frequency === 'custom'+ ? [+ ...FREQUENCY_OPTIONS,+ {+ value: 'custom',+ days: survey.iteration_frequency_days ?? undefined,+ label: `Every ${survey.iteration_frequency_days} days`,+ },+ ]+ : FREQUENCY_OPTIONSconst iterationCount = survey.iteration_count ?? DEFAULT_ITERATION_COUNTconst seenSurveyWaitPeriodInDays = conditions.seenSurveyWaitPeriodInDays ?? null@@ -82,6 +95,10 @@ export function WhenStep(): JSX.Element {}const setFrequency = (value: string): void => {+ if (value === 'custom') {+ // Already the active cadence — nothing to change.+ return+ }const option = FREQUENCY_OPTIONS.find((opt) => opt.value === value)if (value === 'once') {setSurveyValue('schedule', SurveySchedule.Once)@@ -281,7 +298,7 @@ export function WhenStep(): JSX.Element {<WizardSectiontitle="How often should this survey show?"- description="How many times the same user can see this survey, and how often."+ description="How many times this survey repeats, and how often. Repeats count from the launch date, so all users become eligible again at the same time."descriptionClassName="text-sm">{repeatsOnEveryEvent ? (@@ -297,7 +314,7 @@ export function WhenStep(): JSX.Element {<LemonSegmentedButtonvalue={frequency}onChange={setFrequency}- options={FREQUENCY_OPTIONS.map((opt) => ({+ options={frequencyOptions.map((opt) => ({...opt,tooltip:opt.value === recommendedFrequency.valuediff --git a/posthog/tasks/test/test_update_survey_iteration.py b/posthog/tasks/test/test_update_survey_iteration.pyindex 8cb5047e7cf8..6745d7b58cb3 100644--- a/posthog/tasks/test/test_update_survey_iteration.py+++ b/posthog/tasks/test/test_update_survey_iteration.py@@ -53,6 +53,23 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):self.recurring_survey.refresh_from_db()self.assertEqual(self.recurring_survey.current_iteration, 3)+ def test_survey_ends_after_final_iteration(self) -> None:+ self.recurring_survey.start_date = now() - timedelta(days=self.iteration_frequency_days * 3 + 1)+ self.recurring_survey.save()+ self.assertEqual(self.recurring_survey.current_iteration, 1)+ update_survey_iteration()+ self.recurring_survey.refresh_from_db()+ self.assertIsNotNone(self.recurring_survey.end_date)+ self.assertEqual(self.recurring_survey.current_iteration, 1)++ def test_huge_iteration_frequency_does_not_crash_task(self) -> None:+ self.recurring_survey.iteration_count = 1+ self.recurring_survey.iteration_frequency_days = 2_147_483_647+ self.recurring_survey.save()+ update_survey_iteration()+ self.recurring_survey.refresh_from_db()+ self.assertIsNone(self.recurring_survey.end_date)+def test_can_guard_for_current_survey_iteration_overflow(self) -> None:self.recurring_survey.start_date = now() - timedelta(self.iteration_frequency_days * 3)self.recurring_survey.save()diff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.pyindex 97f2de15f414..1fa2e7d67541 100644--- a/posthog/tasks/update_survey_iteration.py+++ b/posthog/tasks/update_survey_iteration.py@@ -1,6 +1,8 @@-from datetime import date+from datetime import date, timedeltafrom typing import Any+from django.utils import timezone+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Survey@@ -10,18 +12,40 @@ def _update_survey_iteration(survey: Survey) -> None:if survey.iteration_start_dates is None or survey.end_date is not None:return+ if _has_final_iteration_ended(survey):+ survey.end_date = timezone.now()+ survey.save(update_fields=["end_date"])+ return+current_iteration = _get_current_iteration(survey)if (- current_iteration != survey.current_iteration+ current_iteration > 0+ and current_iteration != survey.current_iterationand survey.iteration_start_dates is not Noneand 0 < len(survey.iteration_start_dates)):- survey.current_iteration = max(_get_current_iteration(survey), 1)+ survey.current_iteration = current_iterationsurvey.current_iteration_start_date = survey.iteration_start_dates[survey.current_iteration - 1]survey.internal_targeting_flag = _get_targeting_flag(survey)survey.save(update_fields=["current_iteration", "current_iteration_start_date", "internal_targeting_flag_id"])+def _has_final_iteration_ended(survey: Survey) -> bool:+ if not survey.iteration_start_dates or not survey.iteration_frequency_days:+ return False++ last_iteration_start = survey.iteration_start_dates[-1]+ if last_iteration_start is None:+ return False++ try:+ final_iteration_end = last_iteration_start.date() + timedelta(days=survey.iteration_frequency_days)+ except OverflowError:+ # iteration_frequency_days is not capped by the API; a huge value must not crash the task+ return False+ return date.today() > final_iteration_end++def _get_targeting_flag(survey: Survey) -> FeatureFlag | Any:existing_targeting_flag: FeatureFlag | None = survey.internal_targeting_flaguser_submitted_dismissed_filter = {