Skip to content

: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.

fix(surveys): stop auto-closing surveys that are not on a recurring schedule (#102444)

Ben Leac6c89d67c18f
diff --git a/posthog/tasks/test/test_update_survey_iteration.py b/posthog/tasks/test/test_update_survey_iteration.py
index 93cdc58f72fd..d827b6d9ab53 100644
--- a/posthog/tasks/test/test_update_survey_iteration.py
+++ b/posthog/tasks/test/test_update_survey_iteration.py
@@ -39,6 +39,7 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):
type="popover",
questions=[{"type": "open", "question": "What's a survey?"}],
start_date=datetime.now() - timedelta(days=61),
+ schedule=Survey.Schedule.RECURRING,
iteration_count=3,
iteration_frequency_days=self.iteration_frequency_days,
)
@@ -66,6 +67,14 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):
self.assertIsNotNone(self.recurring_survey.end_date)
self.assertEqual(self.recurring_survey.current_iteration, 1)
+ def test_survey_with_once_schedule_is_not_ended_by_stale_iteration_fields(self) -> None:
+ self.recurring_survey.schedule = Survey.Schedule.ONCE
+ self.recurring_survey.start_date = now() - timedelta(days=self.iteration_frequency_days * 3 + 1)
+ self.recurring_survey.save()
+ update_survey_iteration()
+ self.recurring_survey.refresh_from_db()
+ self.assertIsNone(self.recurring_survey.end_date)
+
def test_survey_end_after_final_iteration_is_logged_as_system_activity(self) -> None:
self.recurring_survey.start_date = now() - timedelta(days=self.iteration_frequency_days * 3 + 1)
self.recurring_survey.save()
diff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.py
index 5922e6100088..cfcbaf46236a 100644
--- a/posthog/tasks/update_survey_iteration.py
+++ b/posthog/tasks/update_survey_iteration.py
@@ -145,8 +145,13 @@ def _get_current_iteration(survey: Survey) -> int:
def update_survey_iteration() -> None:
+ # `schedule` is the user's intent. The iteration_* columns can outlive it on rows that predate
+ # the field or were written by an API client, so they alone do not make a survey recurring.
surveys_with_recurring_schedules = Survey.objects.filter(
- start_date__isnull=False, end_date__isnull=True, iteration_count__isnull=False
+ start_date__isnull=False,
+ end_date__isnull=True,
+ iteration_count__isnull=False,
+ schedule=Survey.Schedule.RECURRING,
).only("id", "iteration_count", "iteration_start_dates")
for survey in list(surveys_with_recurring_schedules):
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index ada726c76e5b..1ade1bf83c02 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -1701,8 +1701,26 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
}
)
+ self._reconcile_schedule_with_iterations(data)
return data
+ @staticmethod
+ def _reconcile_schedule_with_iterations(validated_data: dict) -> None:
+ # The edit form reads `schedule` while update_survey_iteration reads the iteration columns,
+ # so the two must agree or the survey repeats while presenting itself as one-shot.
+ schedule = validated_data.get("schedule")
+ if (
+ schedule is None
+ and validated_data.get("iteration_count")
+ and validated_data.get("iteration_frequency_days")
+ ):
+ # Iteration fields alone have always configured repeats, so keep the caller's values.
+ validated_data["schedule"] = Survey.Schedule.RECURRING
+ elif "schedule" in validated_data and schedule != Survey.Schedule.RECURRING:
+ # An explicit null counts as non-recurring: the edit form reads it as "Once".
+ validated_data["iteration_count"] = None
+ validated_data["iteration_frequency_days"] = None
+
def create(self, validated_data):
if "remove_targeting_flag" in validated_data:
validated_data.pop("remove_targeting_flag")
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index b0e165438d85..ad62ce016920 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -5251,6 +5251,59 @@ class TestSurveysRecurringIterations(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["detail"] == "Cannot change survey recurrence to 1, should be at least 2"
+ @parameterized.expand(
+ [
+ ("once", "once"),
+ ("null", None),
+ ]
+ )
+ def test_switching_schedule_to_non_recurring_clears_iteration_fields(self, _name: str, schedule: Optional[str]):
+ survey = self._create_recurring_survey()
+ self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey.id}/",
+ data={"start_date": datetime.now(), "iteration_count": 2, "iteration_frequency_days": 30},
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey.id}/",
+ data={"schedule": schedule},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ response_data = response.json()
+ assert response_data["schedule"] == schedule
+ assert response_data["iteration_count"] is None
+ assert response_data["iteration_frequency_days"] is None
+ assert response_data["iteration_start_dates"] == []
+ assert response_data["current_iteration"] is None
+
+ @parameterized.expand(
+ [
+ ("schedule_omitted", {}),
+ ("schedule_null", {"schedule": None}),
+ ]
+ )
+ def test_setting_iterations_without_a_schedule_marks_the_survey_recurring(self, _name: str, schedule_payload: dict):
+ survey = self._create_non_recurring_survey()
+ assert survey.schedule == Survey.Schedule.ONCE
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/surveys/{survey.id}/",
+ data={
+ "start_date": datetime.now(),
+ "iteration_count": 2,
+ "iteration_frequency_days": 30,
+ **schedule_payload,
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ response_data = response.json()
+ assert response_data["schedule"] == "recurring"
+ assert response_data["iteration_count"] == 2
+ assert response_data["iteration_frequency_days"] == 30
+ assert len(response_data["iteration_start_dates"]) == 2
+
def test_can_handle_non_nil_current_iteration(self):
survey = self._create_non_recurring_survey()
survey.current_iteration = 2
@@ -6764,6 +6817,38 @@ class TestSurveyBulkDuplication(APIBaseTest):
# Generic condition fields SHOULD be copied
assert duplicated.conditions.get("url") == "https://example.com"
+ @parameterized.expand(
+ [
+ ("once_with_stale_iterations", Survey.Schedule.ONCE, None, None),
+ ("recurring", Survey.Schedule.RECURRING, 3, 30),
+ ]
+ )
+ def test_bulk_duplicate_reconciles_schedule_with_iteration_fields(
+ self, _name: str, schedule: str, expected_count: Optional[int], expected_frequency: Optional[int]
+ ) -> None:
+ source = Survey.objects.create(
+ team=self.team,
+ name=f"Source {schedule}",
+ type="popover",
+ questions=[{"type": "open", "question": "Test?"}],
+ schedule=schedule,
+ iteration_count=3,
+ iteration_frequency_days=30,
+ created_by=self.user,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.project_id}/surveys/{source.id}/duplicate_to_projects/",
+ data={"target_team_ids": [self.team2.id]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ duplicated = Survey.objects.get(team=self.team2)
+ assert duplicated.schedule == schedule
+ assert duplicated.iteration_count == expected_count
+ assert duplicated.iteration_frequency_days == expected_frequency
+
@parameterized.expand(
[
(