: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): keep resumed recurring surveys open and show why surveys auto-stop (#130441)
Lucas Faria38751001b590
diff --git a/frontend/src/scenes/surveys/surveyActivityDescriber.test.tsx b/frontend/src/scenes/surveys/surveyActivityDescriber.test.tsxindex dfc229cc61d4..0b8ecb245324 100644--- a/frontend/src/scenes/surveys/surveyActivityDescriber.test.tsx+++ b/frontend/src/scenes/surveys/surveyActivityDescriber.test.tsx@@ -1,7 +1,10 @@import { render } from '@testing-library/react'+import { Provider } from 'kea'-import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'+import { ActivityLogRow } from 'lib/components/ActivityLog/ActivityLogRow'+import { ActivityChange, ActivityLogItem, humanize } from 'lib/components/ActivityLog/humanizeActivity'+import { initKeaTests } from '~/test/init'import {ActivityScope,BasicSurveyQuestion,@@ -295,4 +298,53 @@ describe('surveyActivityDescriber', () => {const { description } = surveyActivityDescriber(questionsChange(before, after))expect(getTextContent(<>{description}</>)).toContain(expected)})++ test.each([+ [+ 'its schedule ended',+ { job_type: 'survey_schedule_ended', job_id: '1', payload: {} },+ 'Example survey after its last scheduled repeat',+ ],+ [+ 'it reached its response limit',+ { job_type: 'survey_responses_limit_reached', job_id: '1', payload: { responses_limit: 300 } },+ 'Example survey after reaching its limit of 300 responses',+ ],+ ['a person stopped it', null, 'stoppedExample survey'],+ ])('says why the survey stopped when %s', (_, trigger, expected) => {+ initKeaTests()+ // Activity rows render the summary, so assert on the row rather than the description alone.+ const [humanized] = humanize(+ [+ {+ activity: 'updated',+ created_at: '2026-01-01T00:00:00Z',+ scope: ActivityScope.SURVEY,+ item_id: '1',+ is_system: true,+ detail: {+ name: 'Example survey',+ changes: [+ {+ type: ActivityScope.SURVEY,+ action: 'created',+ field: 'end_date',+ before: null,+ after: '2026-01-01T00:00:00Z',+ },+ ],+ merge: null,+ trigger,+ },+ },+ ],+ () => surveyActivityDescriber+ )+ const row = getTextContent(+ <Provider>+ <ActivityLogRow logItem={humanized} />+ </Provider>+ )+ expect(row.replace(/\s+/g, ' ')).toMatch(new RegExp(`${expected}$`))+ })})diff --git a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx b/frontend/src/scenes/surveys/surveyActivityDescriber.tsxindex b0b357f6cd28..7b7ddacb3279 100644--- a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx+++ b/frontend/src/scenes/surveys/surveyActivityDescriber.tsx@@ -8,13 +8,14 @@ import {ChangeMapping,Description,HumanizedChange,+ Trigger,activityLogSummary,defaultDescriber,detectBoolean,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'-import { truncate } from 'lib/utils/strings'+import { pluralize, truncate } from 'lib/utils/strings'import { urls } from 'scenes/urls'import {@@ -420,11 +421,17 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotificationif (changes.length === 1) {const { field, description } = changes[0]const preposition = field === 'conditions' ? 'for' : getPreposition(field)+ const target = (+ <>+ {surveyLink}+ {systemStopReason(logItem.detail.trigger)}+ </>+ )return {- summary: activityLogSummary(logItem, <SentenceList listParts={summaryChanges} />, surveyLink, preview),+ summary: activityLogSummary(logItem, <SentenceList listParts={summaryChanges} />, target, preview),description: (<>- {user} {description} {preposition} {surveyLink}+ {user} {description} {preposition} {target}</>),}@@ -448,6 +455,17 @@ export function surveyActivityDescriber(logItem: ActivityLogItem, asNotificationreturn defaultDescriber(logItem, asNotification, surveyLink)}+function systemStopReason(trigger: Trigger | null): string | null {+ switch (trigger?.job_type) {+ case 'survey_schedule_ended':+ return ' after its last scheduled repeat'+ case 'survey_responses_limit_reached':+ return ` after reaching its limit of ${pluralize(trigger.payload.responses_limit, 'response')}`+ default:+ return null+ }+}+export function getPreposition(field: string): string {switch (field) {case 'questions':diff --git a/posthog/tasks/stop_surveys_reached_target.py b/posthog/tasks/stop_surveys_reached_target.pyindex a0d12666c0da..e016609a8601 100644--- a/posthog/tasks/stop_surveys_reached_target.py+++ b/posthog/tasks/stop_surveys_reached_target.py@@ -11,9 +11,9 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDT+from posthog.tasks.survey_system_stop import log_survey_stopped_by_systemfrom products.surveys.backend.models import Survey@@ -61,29 +61,18 @@ def _stop_survey_if_reached_limit(survey: Survey, responses_count: int) -> None:if responses_count < survey.responses_limit:return+ responses_limit = survey.responses_limitsurvey.end_date = timezone.now()survey.responses_limit = Nonesurvey.save(update_fields=["end_date", "responses_limit"])- _log_survey_closed_by_responses_limit(survey)+ _log_survey_closed_by_responses_limit(survey, responses_limit)-def _log_survey_closed_by_responses_limit(survey: Survey) -> None:+def _log_survey_closed_by_responses_limit(survey: Survey, responses_limit: int) -> None:# This task saves directly on the model, bypassing the API viewset that writes# activity-log entries. Without this, the survey stops with no trace and the user# has no way to see why. Mirror the schedule-close entry in update_survey_iteration.- log_activity(- organization_id=survey.team.organization_id,- team_id=survey.team_id,- user=None, # system action: renders as PostHog in the activity log- was_impersonated=False,- item_id=survey.id,- scope="Survey",- activity="updated",- detail=Detail(- name=survey.name,- changes=[Change(type="Survey", field="end_date", action="created", after=survey.end_date)],- ),- )+ log_survey_stopped_by_system(survey, "survey_responses_limit_reached", {"responses_limit": responses_limit})def stop_surveys_reached_target() -> None:diff --git a/posthog/tasks/survey_system_stop.py b/posthog/tasks/survey_system_stop.pynew file mode 100644index 000000000000..6cd4390b5236--- /dev/null+++ b/posthog/tasks/survey_system_stop.py@@ -0,0 +1,22 @@+from typing import Any++from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity++from products.surveys.backend.models import Survey+++def log_survey_stopped_by_system(survey: Survey, job_type: str, payload: dict[str, Any]) -> None:+ log_activity(+ organization_id=survey.team.organization_id,+ team_id=survey.team_id,+ user=None, # system action: renders as PostHog in the activity log+ was_impersonated=False,+ item_id=survey.id,+ scope="Survey",+ activity="updated",+ detail=Detail(+ name=survey.name,+ changes=[Change(type="Survey", field="end_date", action="created", after=survey.end_date)],+ trigger=Trigger(job_type=job_type, job_id=str(survey.id), payload=payload),+ ),+ )diff --git a/posthog/tasks/test/test_stop_surveys_reached_target.py b/posthog/tasks/test/test_stop_surveys_reached_target.pyindex 48f49b53b2ea..b25b0076d80c 100644--- a/posthog/tasks/test/test_stop_surveys_reached_target.py+++ b/posthog/tasks/test/test_stop_surveys_reached_target.py@@ -277,3 +277,8 @@ class TestStopSurveysReachedTarget(TestCase, ClickhouseTestMixin):assert change["field"] == "end_date"assert change["action"] == "created"assert change["after"] is not None+ assert log.detail["trigger"] == {+ "job_type": "survey_responses_limit_reached",+ "job_id": str(survey.id),+ "payload": {"responses_limit": 1},+ }diff --git a/posthog/tasks/test/test_update_survey_iteration.py b/posthog/tasks/test/test_update_survey_iteration.pyindex d827b6d9ab53..1a4b4ace32ac 100644--- a/posthog/tasks/test/test_update_survey_iteration.py+++ b/posthog/tasks/test/test_update_survey_iteration.py@@ -6,9 +6,11 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCasefrom django.utils.timezone import now+from parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, Team, User-from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, log_activityfrom posthog.tasks.update_survey_iteration import update_survey_iterationfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequest@@ -91,6 +93,46 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):self.assertEqual(change["field"], "end_date")self.assertEqual(change["action"], "created")self.assertIsNotNone(change["after"])+ self.assertEqual(+ log.detail["trigger"],+ {+ "job_type": "survey_schedule_ended",+ "job_id": str(self.recurring_survey.id),+ "payload": {"iteration_count": 3, "iteration_frequency_days": self.iteration_frequency_days},+ },+ )++ @parameterized.expand(+ [+ # Resuming a survey the scheduler closed must stick, or it closes again on the next run.+ ("resumed_after_schedule_ended", 2, False),+ ("resumed_before_schedule_ended", 10, True),+ ]+ )+ def test_person_resuming_survey(self, _name: str, resumed_days_ago: int, expect_closed: bool) -> None:+ self.recurring_survey.start_date = now() - timedelta(days=self.iteration_frequency_days * 3 + 5)+ self.recurring_survey.save()+ log_activity(+ organization_id=self.org.id,+ team_id=self.team.id,+ user=self.user,+ was_impersonated=False,+ item_id=self.recurring_survey.id,+ scope="Survey",+ activity="updated",+ detail=Detail(+ name=self.recurring_survey.name,+ changes=[Change(type="Survey", field="end_date", action="changed", before=now(), after=None)],+ ),+ )+ ActivityLog.objects.filter(item_id=str(self.recurring_survey.id)).update(+ created_at=now() - timedelta(days=resumed_days_ago)+ )++ update_survey_iteration()++ self.recurring_survey.refresh_from_db()+ self.assertEqual(self.recurring_survey.end_date is not None, expect_closed)def test_huge_iteration_frequency_does_not_crash_task(self) -> None:self.recurring_survey.iteration_count = 1diff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.pyindex cfcbaf46236a..053fcd2411de 100644--- a/posthog/tasks/update_survey_iteration.py+++ b/posthog/tasks/update_survey_iteration.py@@ -2,7 +2,8 @@ from datetime import date, timedeltafrom django.utils import timezone-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.tasks.survey_system_stop import log_survey_stopped_by_systemfrom products.feature_flags.backend.facade.api import create_flag, update_flagfrom products.feature_flags.backend.facade.filters import replace_release_conditions@@ -15,10 +16,12 @@ 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"])- _log_survey_closed_by_schedule(survey)+ final_iteration_end = _get_final_iteration_end(survey)+ if final_iteration_end is not None and date.today() > final_iteration_end:+ if not _was_resumed_by_a_person_after(survey, final_iteration_end):+ survey.end_date = timezone.now()+ survey.save(update_fields=["end_date"])+ _log_survey_closed_by_schedule(survey)returncurrent_iteration = _get_current_iteration(survey)@@ -38,35 +41,39 @@ def _log_survey_closed_by_schedule(survey: Survey) -> None:# Record a system activity-log entry so the survey's history explains why it stopped.# Without this, the scheduler's direct save() leaves no trace, and a user who removes# the end date only ever sees their own removals logged — never the automatic close.- log_activity(- organization_id=survey.team.organization_id,- team_id=survey.team_id,- user=None, # system action: renders as PostHog in the activity log- was_impersonated=False,- item_id=survey.id,- scope="Survey",- activity="updated",- detail=Detail(- name=survey.name,- changes=[Change(type="Survey", field="end_date", action="created", after=survey.end_date)],- ),+ log_survey_stopped_by_system(+ survey,+ "survey_schedule_ended",+ {"iteration_count": survey.iteration_count, "iteration_frequency_days": survey.iteration_frequency_days},)-def _has_final_iteration_ended(survey: Survey) -> bool:+def _get_final_iteration_end(survey: Survey) -> date | None:if not survey.iteration_start_dates or not survey.iteration_frequency_days:- return False+ return Nonelast_iteration_start = survey.iteration_start_dates[-1]if last_iteration_start is None:- return False+ return Nonetry:- final_iteration_end = last_iteration_start.date() + timedelta(days=survey.iteration_frequency_days)+ return 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+ return None+++def _was_resumed_by_a_person_after(survey: Survey, day: date) -> bool:+ # The iteration dates stay anchored to start_date, so a survey resumed after its schedule ended+ # still looks finished. Closing it again would silently undo the person's resume.+ return ActivityLog.objects.filter(+ team_id=survey.team_id,+ scope="Survey",+ item_id=str(survey.id),+ is_system=False,+ created_at__date__gt=day,+ detail__changes__contains=[{"field": "end_date", "after": None}],+ ).exists()def _get_targeting_flag(survey: Survey) -> FeatureFlag: