: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
feat: Coming Soon waitlist surveys (gated) (#65180)
Joe Martind21beb2b7b4f
diff --git a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsxindex add9b4db3e1e..1c410adf0ed0 100644--- a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx+++ b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx@@ -6,6 +6,7 @@ import { LemonBanner, LemonButton, LemonInput, LemonSwitch, LemonTextArea, Linkimport { BasicCard } from 'lib/components/Cards/BasicCard'import { FEATURE_FLAGS } from 'lib/constants'+import { useAnchor } from 'lib/hooks/useAnchor'import { IconLink } from 'lib/lemon-ui/icons'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'import { Label } from 'lib/ui/Label/Label'@@ -46,6 +47,10 @@ export function FeaturePreviews(): JSX.Element {useLayoutEffect(() => loadEarlyAccessFeatures(), [loadEarlyAccessFeatures])+ // Cards render only after the async feature fetch, so the scene-level anchor handling+ // fires too early — defer the scroll + highlight until the cards exist.+ useAnchor(rawEarlyAccessFeaturesLoading ? '' : window.location.hash)+const betaFeatures = filteredEarlyAccessFeatures.filter((f) => f.stage === 'beta')const shouldShowEmptyState =filteredEarlyAccessFeatures.length === 0 && !rawEarlyAccessFeaturesLoading && !searchTerm@@ -108,6 +113,10 @@ export function FeaturePreviewsComingSoon(): JSX.Element {useLayoutEffect(() => loadEarlyAccessFeatures(), [loadEarlyAccessFeatures])+ // Cards render only after the async feature fetch, so the scene-level anchor handling+ // fires too early — defer the scroll + highlight until the cards exist.+ useAnchor(rawEarlyAccessFeaturesLoading ? '' : window.location.hash)+const conceptFeatures = filteredEarlyAccessFeatures.filter((f) => f.stage === 'concept')return (@@ -153,9 +162,74 @@ function PreviewCard({ feature, title, description, actions, children }: Preview}function ConceptPreview({ feature }: { feature: EnrichedEarlyAccessFeature }): JSX.Element {- const { updateEarlyAccessFeatureEnrollment, copyExternalFeaturePreviewLink } = useActions(featurePreviewsLogic)+ const { updateEarlyAccessFeatureEnrollment, copyExternalFeaturePreviewLink, submitConceptSurvey } =+ useActions(featurePreviewsLogic)+ const { waitlistSurveysEnabled, conceptSurveySubmissions } = useValues(featurePreviewsLogic)const { flagKey, enabled, name, description } = feature+ const [email, setEmail] = useState('')++ // When the gate is on and the feature has a linked waitlist survey, collect an email+ // (recorded as a survey response) instead of the one-click, login-tied enrollment.+ const surveyId = feature.payload?.survey_id+ const hasWaitlistSurvey = waitlistSurveysEnabled && !!surveyId+ // `enabled` covers users who registered interest before the survey era — the+ // migration command moves them into the survey, so don't ask them again.+ const surveySubmitted = !!conceptSurveySubmissions[flagKey] || enabled++ let actions: JSX.Element+ if (hasWaitlistSurvey) {+ actions = surveySubmitted ? (+ // role="status" makes the confirmation a live region: the form (and its focused+ // button) unmounts on submit, so without it screen readers announce nothing.+ <span role="status" className="flex items-center gap-1 text-success font-medium">+ <IconCheck /> Thanks — we'll email you when it's ready.+ </span>+ ) : (+ <form+ className="flex items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault()+ if (email) {+ submitConceptSurvey(flagKey, email)+ }+ }}+ >+ <LemonInput+ type="email"+ value={email}+ onChange={setEmail}+ placeholder="[email protected]"+ aria-label="Email address"+ autoComplete="email"+ size="small"+ />+ <LemonButton+ type="primary"+ size="small"+ htmlType="submit"+ disabledReason={!email ? 'Enter your email' : undefined}+ >+ Get notified+ </LemonButton>+ </form>+ )+ } else {+ actions = (+ <LemonButton+ type="primary"+ disabledReason={+ enabled && "You have already expressed your interest. We'll contact you when it's ready"+ }+ onClick={() => updateEarlyAccessFeatureEnrollment(flagKey, true, feature.stage)}+ size="small"+ sideIcon={enabled ? <IconCheck /> : <IconBell />}+ className="w-fit"+ >+ {enabled ? 'Registered' : 'Get notified'}+ </LemonButton>+ )+ }return (<PreviewCard@@ -175,22 +249,7 @@ function ConceptPreview({ feature }: { feature: EnrichedEarlyAccessFeature }): J{description || <span className="text-tertiary">No description</span>}</p>}- actions={- <div className="flex flex-col gap-2">- <LemonButton- type="primary"- disabledReason={- enabled && "You have already expressed your interest. We'll contact you when it's ready"- }- onClick={() => updateEarlyAccessFeatureEnrollment(flagKey, true, feature.stage)}- size="small"- sideIcon={enabled ? <IconCheck /> : <IconBell />}- className="w-fit"- >- {enabled ? 'Registered' : 'Get notified'}- </LemonButton>- </div>- }+ actions={actions}/>)}diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.tsindex 63a9cd9b17ee..2338a57abe9b 100644--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts@@ -160,6 +160,102 @@ describe('featurePreviewsLogic - conceptEnrollments reducer', () => {})})+describe('featurePreviewsLogic - submitConceptSurvey', () => {+ let logic: ReturnType<typeof featurePreviewsLogic.build>+ const mockCapture = jest.fn()+ const mockUpdateEnrollment = jest.fn()+ let originalImpersonatedSession: boolean | undefined++ afterEach(() => {+ window.IMPERSONATED_SESSION = originalImpersonatedSession+ })++ beforeEach(() => {+ jest.clearAllMocks()+ originalImpersonatedSession = window.IMPERSONATED_SESSION+ ;(posthog as any).capture = mockCapture+ ;(posthog as any).updateEarlyAccessFeatureEnrollment = mockUpdateEnrollment++ useMocks({+ post: {+ 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],+ },+ })+ initKeaTests()+ logic = featurePreviewsLogic()+ logic.mount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)+ })++ test('captures the survey response, records enrollment, and marks the flag submitted', async () => {+ logic.actions.loadEarlyAccessFeaturesSuccess([+ {+ flagKey: 'concept-flag',+ stage: 'concept',+ payload: { survey_id: 'survey-123', survey_question_id: 'question-456' },+ } as any,+ ])++ logic.actions.submitConceptSurvey('concept-flag', '[email protected]')++ expect(mockCapture).toHaveBeenCalledWith('survey sent', {+ $survey_id: 'survey-123',+ $survey_response: '[email protected]',+ '$survey_response_question-456': '[email protected]',+ })+ expect(mockUpdateEnrollment).toHaveBeenCalledWith('concept-flag', true, 'concept')+ await expectLogic(logic)+ .toDispatchActions(['conceptSurveySubmitted'])+ .toMatchValues({ conceptSurveySubmissions: { 'concept-flag': true } })+ })++ test('captures without a per-question key when the payload has no question id', () => {+ logic.actions.loadEarlyAccessFeaturesSuccess([+ { flagKey: 'concept-flag', stage: 'concept', payload: { survey_id: 'survey-123' } } as any,+ ])++ logic.actions.submitConceptSurvey('concept-flag', '[email protected]')++ expect(mockCapture).toHaveBeenCalledWith('survey sent', {+ $survey_id: 'survey-123',+ $survey_response: '[email protected]',+ })+ })++ test('shows an error and does not mark submitted when the feature has no linked survey', async () => {+ logic.actions.loadEarlyAccessFeaturesSuccess([+ { flagKey: 'concept-flag', stage: 'concept', payload: {} } as any,+ ])++ logic.actions.submitConceptSurvey('concept-flag', '[email protected]')++ expect(mockCapture).not.toHaveBeenCalled()+ expect(mockUpdateEnrollment).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith(+ "This feature isn't accepting sign-ups yet. Please try again later."+ )+ await expectLogic(logic).toMatchValues({ conceptSurveySubmissions: {} })+ })++ test('does not capture anything during an impersonated session', async () => {+ window.IMPERSONATED_SESSION = true+ logic.actions.loadEarlyAccessFeaturesSuccess([+ {+ flagKey: 'concept-flag',+ stage: 'concept',+ payload: { survey_id: 'survey-123' },+ } as any,+ ])++ logic.actions.submitConceptSurvey('concept-flag', '[email protected]')++ expect(mockCapture).not.toHaveBeenCalled()+ expect(mockUpdateEnrollment).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith('Cannot sign up for a waitlist while impersonating a user')+ await expectLogic(logic).toMatchValues({ conceptSurveySubmissions: {} })+ })+})+describe('featurePreviewsLogic - updateEarlyAccessFeatureEnrollment (impersonated session)', () => {let logic: ReturnType<typeof featurePreviewsLogic.build>const mockUpdateEnrollment = jest.fn()diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsxindex d953bd941ee1..be48a48f5f90 100644--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'import { EarlyAccessFeature, posthog } from 'posthog-js'import { supportLogic } from 'lib/components/Support/supportLogic'-import { FeatureFlagKey } from 'lib/constants'+import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -143,6 +143,12 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([cancelEarlyAccessFeatureFeedback: true,submitEarlyAccessFeatureFeedback: (message: string) => ({ message }),copyExternalFeaturePreviewLink: (flagKey: string) => ({ flagKey }),+ // Coming Soon (concept) waitlist: submit an email to the feature's linked survey+ // instead of the one-click enrollment.+ submitConceptSurvey: (flagKey: string, email: string) => ({ flagKey, email }),+ // Fired by the submitConceptSurvey listener once the response has actually been+ // captured, so the "thanks" state can't show when submission failed.+ conceptSurveySubmitted: (flagKey: string) => ({ flagKey }),}),loaders(({ values }) => ({rawEarlyAccessFeatures: [@@ -215,6 +221,14 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([},},],+ // Tracks which concept features the user has submitted the waitlist email for,+ // so the card can show a "thanks" state.+ conceptSurveySubmissions: [+ {} as Record<string, boolean>,+ {+ conceptSurveySubmitted: (state, { flagKey }) => ({ ...state, [flagKey]: true }),+ },+ ],}),listeners(({ values, actions }) => ({updateEarlyAccessFeatureEnrollment: ({ flagKey, enabled, stage }) => {@@ -252,6 +266,32 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([copyExternalFeaturePreviewLink: ({ flagKey }) => {void copyToClipboard(urls.absolute(`/settings/user-feature-previews#${flagKey}`))},+ submitConceptSurvey: ({ flagKey, email }) => {+ // Keep the survey response and the enrollment person property in sync — the+ // enrollment listener below refuses impersonated sessions, so bail before+ // capturing anything.+ if (window.IMPERSONATED_SESSION) {+ lemonToast.error('Cannot sign up for a waitlist while impersonating a user')+ return+ }+ const feature = values.rawEarlyAccessFeatures.find((f) => f.flagKey === flagKey)+ const payload = (feature as any)?.payload as Record<string, any> | undefined+ const surveyId = payload?.survey_id+ if (!surveyId) {+ lemonToast.error("This feature isn't accepting sign-ups yet. Please try again later.")+ return+ }+ const surveyQuestionId = payload?.survey_question_id+ const properties: Record<string, any> = { $survey_id: surveyId, $survey_response: email }+ if (surveyQuestionId) {+ properties[`$survey_response_${surveyQuestionId}`] = email+ }+ posthog.capture('survey sent', properties)+ actions.conceptSurveySubmitted(flagKey)+ // Also record the enrollment so the "registered" state persists across+ // reloads (person property), matching the pre-survey behavior.+ actions.updateEarlyAccessFeatureEnrollment(flagKey, true, 'concept')+ },})),selectors({earlyAccessFeatures: [@@ -297,5 +337,12 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([return search(earlyAccessFeatures, searchTerm)},],++ // When enabled, concept-stage ("Coming Soon") items collect an email via their+ // linked survey instead of the one-click enrollment.+ waitlistSurveysEnabled: [+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.COMING_SOON_WAITLIST_SURVEYS],+ ],}),])diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex ee1db45eecf4..225d425a0296 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -158,6 +158,7 @@ export const RETENTION_FIRST_EVER_OCCURRENCE = 'retention_first_ever_occurrence'export const FEATURE_FLAGS = {// Eternal feature flags, shouldn't be removed, helpful for debugging/maintenance reasonsBILLING_FORECASTING_ISSUES: 'billing-forecasting-issues', // owner: #team-billing, see `Billing.tsx`, used to raise a warning when billing is having problems+ COMING_SOON_WAITLIST_SURVEYS: 'coming-soon-waitlist-surveys', // owner: #team-growth, see `FeaturePreviews.tsx`, swaps concept-stage one-click for an email waitlist surveyHOG: 'hog', // owner: #team-data-tools, see `DebugScene.tsx` and also insightsNAV_PANEL_CAMPAIGN: 'nav-panel-campaign', // owner: #team-growth, sidebar promotional campaign, payload-driven. See NavPanelAdvertisement.tsxQUERY_TIMINGS: 'query-timings', // owner: #team-analytics-platform, usage: see `dataTableLogic.ts`diff --git a/posthog/tasks/early_access_feature.py b/posthog/tasks/early_access_feature.pyindex dee88d5f0044..30a52fcb9140 100644--- a/posthog/tasks/early_access_feature.py+++ b/posthog/tasks/early_access_feature.py@@ -1,4 +1,7 @@-from typing import Any+from typing import Any, Optional++from django.db import IntegrityError, connection, transaction+from django.utils import timezoneimport structlogimport posthoganalytics@@ -9,14 +12,121 @@ from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContextfrom posthog.hogql.query import execute_hogql_queryfrom posthog.cloud_utils import is_cloud+from posthog.models import Teamfrom posthog.scoping_audit import skip_team_scope_auditfrom products.early_access_features.backend.models import EarlyAccessFeature+from products.surveys.backend.models import Surveylogger = structlog.get_logger(__name__)POSTHOG_TEAM_ID = 2+# Gate for auto-creating a waitlist survey per "Coming Soon" (concept-stage) feature, and+# for showing the email field in-app. Enable for PostHog's own project first.+COMING_SOON_WAITLIST_SURVEYS_FLAG = "coming-soon-waitlist-surveys"+++def coming_soon_waitlist_surveys_enabled(team: Team) -> bool:+ """Whether the auto-survey behavior is enabled for this team (evaluated by project group)."""+ return bool(+ posthoganalytics.feature_enabled(+ COMING_SOON_WAITLIST_SURVEYS_FLAG,+ str(team.id),+ groups={"project": str(team.id)},+ group_properties={"project": {"id": str(team.id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+++def ensure_waitlist_survey_for_feature(instance: EarlyAccessFeature) -> Optional[Survey]:+ """+ Idempotently ensure a concept-stage Early Access Feature has a linked `api` waitlist+ survey, and record its id (+ first question id) on the feature's payload so posthog-js+ consumers (posthog.com/roadmap and the in-app Feature Previews) know where to send the+ email. Returns the survey, or None if not applicable (wrong stage, survey already+ linked, or no flag — callers only need "nothing to do", so the reasons are deliberately+ not distinguished). Does NOT check the gating flag — callers decide that.+ """+ if instance.stage != EarlyAccessFeature.Stage.CONCEPT:+ return None+ if instance.payload and instance.payload.get("survey_id"):+ return None+ feature_flag = instance.feature_flag+ if not feature_flag:+ return None++ # Reuse an existing api survey linked to this flag if one exists (handles re-runs and+ # the (team, name) uniqueness constraint).+ survey = Survey.objects.filter(team=instance.team, linked_flag=feature_flag, type=Survey.SurveyType.API).first()+ if survey is None:+ # Serialize concurrent creates for the same flag (the signal firing on create and+ # again on an immediate edit, or the backfill colliding with the signal) with a+ # transaction-scoped advisory lock. Without it, a task committing between another+ # task's linked-survey check and its name-collision check pushes the second task+ # onto the "(flag-key)" suffixed name, leaving two api surveys linked to one flag.+ with transaction.atomic():+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [instance.team_id, feature_flag.id])+ # Re-check under the lock: the winner may have committed after the check above.+ survey = Survey.objects.filter(+ team=instance.team, linked_flag=feature_flag, type=Survey.SurveyType.API+ ).first()+ if survey is None:+ name = f"{instance.name} waitlist"[:380]+ if Survey.objects.filter(team=instance.team, name=name).exists():+ name = f"{name} ({feature_flag.key})"[:400]+ try:+ # The lock only serializes same-flag creates, so (team, name) can still+ # collide with a survey created concurrently for a different flag. The+ # savepoint keeps the transaction usable so we can adopt or re-raise.+ with transaction.atomic():+ survey = Survey.objects.create(+ team=instance.team,+ name=name,+ description=f"Waitlist sign-ups for the upcoming {instance.name} feature.",+ type=Survey.SurveyType.API,+ linked_flag=feature_flag,+ questions=[+ {+ "type": "open",+ "question": f"Enter your email and we'll let you know when {instance.name} is ready.",+ "optional": False,+ }+ ],+ start_date=timezone.now(),+ )+ except IntegrityError:+ survey = Survey.objects.filter(+ team=instance.team, linked_flag=feature_flag, type=Survey.SurveyType.API+ ).first()+ if survey is None:+ raise++ # `ensure_question_ids` (pre_save) guarantees the question has an id.+ question_id = (survey.questions or [{}])[0].get("id")+ # The merge below is over the payload snapshot read when `instance` was loaded — a+ # concurrent write to a different payload key between that read and this update gets+ # dropped. Fine while this task is the only payload writer besides the API.+ EarlyAccessFeature.objects.filter(pk=instance.pk).update(+ payload={**(instance.payload or {}), "survey_id": str(survey.id), "survey_question_id": question_id}+ )+ return survey+++@shared_task(ignore_result=True, max_retries=3, autoretry_for=(Exception,), retry_backoff=True)+@skip_team_scope_audit+def create_waitlist_survey_for_concept_feature(feature_id: str) -> None:+ try:+ instance = EarlyAccessFeature.objects.select_related("feature_flag", "team").get(id=feature_id)+ except EarlyAccessFeature.DoesNotExist:+ return+ if not coming_soon_waitlist_surveys_enabled(instance.team):+ return+ ensure_waitlist_survey_for_feature(instance)+# Mostly here to help with mocks for testingdef capture_event(event: str, *, distinct_id: str, properties: dict[str, Any]) -> None:diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 10ef84175dad..0e93c873831f 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -21,6 +21,7 @@'posthog.tasks.calculate_cohort.trigger_cohort_backfill_task','posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task','posthog.tasks.demo_create_data.create_data_for_demo_team',+ 'posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature','posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change','posthog.tasks.email.login_from_new_device_notification','posthog.tasks.email.send_async_migration_complete_email',diff --git a/products/early_access_features/backend/apps.py b/products/early_access_features/backend/apps.pyindex 8f60bafd0311..b822ca2af341 100644--- a/products/early_access_features/backend/apps.py+++ b/products/early_access_features/backend/apps.py@@ -7,6 +7,8 @@ class EarlyAccessFeaturesConfig(AppConfig):label = "early_access_features"def ready(self) -> None:+ # Register the post_save signal that auto-creates a waitlist survey for+ # concept-stage ("Coming Soon") features.from posthog.api.file_system.deletion import (register_file_system_type,register_post_delete_hook,@@ -15,6 +17,8 @@ class EarlyAccessFeaturesConfig(AppConfig):from posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Detail, log_activity+ import products.early_access_features.backend.signals # noqa: F401+def _with_feature_flag(queryset):return queryset.select_related("feature_flag")diff --git a/products/early_access_features/backend/management/__init__.py b/products/early_access_features/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/early_access_features/backend/management/commands/__init__.py b/products/early_access_features/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/early_access_features/backend/management/commands/backfill_coming_soon_surveys.py b/products/early_access_features/backend/management/commands/backfill_coming_soon_surveys.pynew file mode 100644index 000000000000..21282656e1ce--- /dev/null+++ b/products/early_access_features/backend/management/commands/backfill_coming_soon_surveys.py@@ -0,0 +1,88 @@+from django.core.management.base import BaseCommand+from django.db import IntegrityError++from products.early_access_features.backend.models import EarlyAccessFeature+++class Command(BaseCommand):+ help = "Backfill an `api` waitlist survey for existing concept-stage ('Coming Soon') Early Access Features"++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, default=None, help="Only process features for this team id")+ parser.add_argument(+ "--force",+ action="store_true",+ help="Skip the coming-soon-waitlist-surveys feature flag gate (process all matching teams)",+ )+ parser.add_argument(+ "--really-run",+ action="store_true",+ help="Actually create surveys. Without this flag, runs in dry-run mode.",+ )++ def handle(self, *args, **options):+ # Imported here so the gate/creation helpers load with the app ready.+ from posthog.tasks.early_access_feature import (+ coming_soon_waitlist_surveys_enabled,+ ensure_waitlist_survey_for_feature,+ )++ team_id = options["team_id"]+ force = options["force"]+ really_run = options["really_run"]++ if not really_run:+ self.stdout.write(self.style.WARNING("Dry run — pass --really-run to create surveys."))++ features = EarlyAccessFeature.objects.select_related("feature_flag", "team").filter(+ stage=EarlyAccessFeature.Stage.CONCEPT+ )+ if team_id is not None:+ features = features.filter(team_id=team_id)++ created = 0+ skipped = 0+ # The gate is a network flag eval — cache it per team so teams with several+ # concept features don't repeat the identical call.+ gate_cache: dict[int, bool] = {}+ for feature in features.iterator():+ if feature.payload and feature.payload.get("survey_id"):+ skipped += 1+ continue+ if not feature.feature_flag:+ skipped += 1+ continue+ if not force:+ if feature.team_id not in gate_cache:+ gate_cache[feature.team_id] = coming_soon_waitlist_surveys_enabled(feature.team)+ if not gate_cache[feature.team_id]:+ skipped += 1+ continue++ if not really_run:+ self.stdout.write(f"[dry-run] would create survey for '{feature.name}' (team {feature.team_id})")+ created += 1+ continue++ try:+ survey = ensure_waitlist_survey_for_feature(feature)+ except IntegrityError:+ # The common same-flag race is handled inside ensure_waitlist_survey_for_feature+ # (advisory lock + adopt-on-IntegrityError). This only fires if that internal+ # adoption also came up empty, e.g. the name collided with a survey created+ # concurrently for a different flag — skip the feature; a re-run picks it up.+ self.stdout.write(+ self.style.WARNING(+ f"'{feature.name}': survey creation raced even after internal adoption, skipping"+ )+ )+ skipped += 1+ continue+ if survey is not None:+ created += 1+ self.stdout.write(self.style.SUCCESS(f"Created survey {survey.id} for '{feature.name}'"))+ else:+ skipped += 1++ verb = "Would create" if not really_run else "Created"+ self.stdout.write(self.style.SUCCESS(f"{verb} {created} survey(s); skipped {skipped}."))diff --git a/products/early_access_features/backend/management/commands/migrate_enrollments_to_waitlist_surveys.py b/products/early_access_features/backend/management/commands/migrate_enrollments_to_waitlist_surveys.pynew file mode 100644index 000000000000..36cdf1f6e82a--- /dev/null+++ b/products/early_access_features/backend/management/commands/migrate_enrollments_to_waitlist_surveys.py@@ -0,0 +1,135 @@+from typing import TYPE_CHECKING, cast++from django.apps import apps+from django.core.management.base import BaseCommand++from products.early_access_features.backend.models import EarlyAccessFeature++if TYPE_CHECKING:+ from products.surveys.backend.models import Survey+++def _survey_model() -> "type[Survey]":+ # Runtime lookup: early_access_features may not import products.surveys directly (tach boundary).+ return cast("type[Survey]", apps.get_model("surveys", "Survey"))+++class Command(BaseCommand):+ help = (+ "Migrate legacy 'Get notified' registrations (the $feature_enrollment/<flag> person property) "+ "into each concept-stage feature's linked waitlist survey as `survey sent` responses, so the "+ "survey is the single waitlist per feature. Skips people who already responded to the survey."+ )++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, default=None, help="Only process features for this team id")+ parser.add_argument(+ "--really-run",+ action="store_true",+ help="Actually capture the survey responses. Without this flag, runs in dry-run mode.",+ )++ def handle(self, *args, **options):+ # Imported here so HogQL and the analytics client load with the app ready.+ import posthoganalytics++ from posthog.hogql import ast+ from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContext+ from posthog.hogql.query import execute_hogql_query++ from posthog.tasks.early_access_feature import capture_event++ team_id = options["team_id"]+ really_run = options["really_run"]++ if not really_run:+ self.stdout.write(self.style.WARNING("Dry run — pass --really-run to capture survey responses."))++ features = EarlyAccessFeature.objects.select_related("feature_flag", "team").filter(+ stage=EarlyAccessFeature.Stage.CONCEPT, feature_flag__isnull=False+ )+ if team_id is not None:+ features = features.filter(team_id=team_id)++ Survey = _survey_model()++ total_migrated = 0+ for feature in features.iterator():+ flag = feature.feature_flag+ if flag is None:+ continue+ survey = Survey.objects.filter(team=feature.team, linked_flag=flag, type=Survey.SurveyType.API).first()+ if survey is None:+ self.stdout.write(f"'{feature.name}': no linked waitlist survey, skipping")+ continue+ question_id = (survey.questions or [{}])[0].get("id")++ # People who registered interest the old way and have an email on their person.+ enrolled = execute_hogql_query(+ """+ SELECT+ properties.email AS email,+ argMax(pdi.distinct_id, created_at) AS distinct_id+ FROM persons+ WHERE properties[{enrollment_key}] = 'true'+ AND notEmpty(properties.email)+ GROUP BY properties.email+ LIMIT {limit}+ """,+ placeholders={+ "enrollment_key": ast.Constant(value=f"$feature_enrollment/{flag.key}"),+ "limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),+ },+ team=feature.team,+ limit_context=LimitContext.QUERY_ASYNC,+ ).results++ if not enrolled:+ self.stdout.write(f"'{feature.name}': no legacy registrations to migrate")+ continue++ # People who already responded to the survey (from any surface) — don't duplicate them.+ responded = execute_hogql_query(+ """+ SELECT DISTINCT lower(JSONExtractString(properties, '$survey_response')) AS email+ FROM events+ WHERE event = 'survey sent'+ AND JSONExtractString(properties, '$survey_id') = {survey_id}+ LIMIT {limit}+ """,+ placeholders={+ "survey_id": ast.Constant(value=str(survey.id)),+ "limit": ast.Constant(value=MAX_SELECT_RETURNED_ROWS),+ },+ team=feature.team,+ limit_context=LimitContext.QUERY_ASYNC,+ ).results+ responded_emails = {row[0] for row in responded if row and row[0]}++ migrated = 0+ for email, distinct_id in enrolled:+ if not email or email.lower() in responded_emails:+ continue+ if really_run:+ properties = {+ "$survey_id": str(survey.id),+ "$survey_response": email,+ "feature_flag_key": flag.key,+ "migrated_from_enrollment": True,+ }+ if question_id:+ properties[f"$survey_response_{question_id}"] = email+ capture_event("survey sent", distinct_id=distinct_id, properties=properties)+ migrated += 1++ total_migrated += migrated+ verb = "would migrate" if not really_run else "migrated"+ self.stdout.write(+ f"'{feature.name}': {verb} {migrated} of {len(enrolled)} legacy registrations "+ f"({len(responded_emails)} already responded)"+ )++ if really_run:+ posthoganalytics.flush()+ verb = "Would migrate" if not really_run else "Migrated"+ self.stdout.write(self.style.SUCCESS(f"{verb} {total_migrated} registration(s) into waitlist surveys."))diff --git a/products/early_access_features/backend/signals.py b/products/early_access_features/backend/signals.pynew file mode 100644index 000000000000..b026354fd654--- /dev/null+++ b/products/early_access_features/backend/signals.py@@ -0,0 +1,32 @@+from django.db import transaction+from django.db.models.signals import post_save+from django.dispatch import receiver++from products.early_access_features.backend.models import EarlyAccessFeature+++@receiver(post_save, sender=EarlyAccessFeature)+def create_waitlist_survey_on_concept_stage(sender, instance: EarlyAccessFeature, **kwargs) -> None:+ """+ When an Early Access Feature is at the `concept` ("Coming Soon") stage and doesn't yet+ have a linked waitlist survey, enqueue a task to create one. The task is gated by the+ `coming-soon-waitlist-surveys` feature flag and is idempotent.++ A signal (rather than a dispatch next to the serializer's stage-change task in api.py)+ is deliberate: it catches every save path — API, Django admin, shell — not just the+ API update flow, so a concept feature can't miss its survey depending on how it was+ edited.++ We enqueue (rather than create inline) because the gate check calls out over the+ network, and we run it `on_commit` so the feature row is durable before the task loads it.+ """+ if instance.stage != EarlyAccessFeature.Stage.CONCEPT:+ return+ if instance.payload and instance.payload.get("survey_id"):+ return++ # Imported lazily to avoid import cycles during app loading.+ from posthog.tasks.early_access_feature import create_waitlist_survey_for_concept_feature++ feature_id = str(instance.id)+ transaction.on_commit(lambda: create_waitlist_survey_for_concept_feature.delay(feature_id))diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.pyindex bc3c7104b9d2..b73885916ffe 100644--- a/products/early_access_features/backend/test/test_early_access_feature.py+++ b/products/early_access_features/backend/test/test_early_access_feature.py@@ -1,9 +1,11 @@import json+from typing import TYPE_CHECKING, castimport unittestfrom posthog.test.base import APIBaseTest, BaseTest, QueryMatchingTest, snapshot_postgres_queries-from unittest.mock import ANY, patch+from unittest.mock import ANY, MagicMock, patch+from django.apps import appsfrom django.core.cache import cachefrom django.test.client import Client@@ -20,6 +22,12 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.models.rbac.access_control import AccessControl+if TYPE_CHECKING:+ from products.surveys.backend.models import Survey as SurveyModel++# Runtime lookup: early_access_features may not import products.surveys directly (tach boundary).+Survey = cast("type[SurveyModel]", apps.get_model("surveys", "Survey"))+class TestEarlyAccessFeatureSiteAppTemplate(unittest.TestCase):def test_site_app_template_escapes_user_controlled_fields(self):@@ -1582,3 +1590,201 @@ class TestEarlyAccessFeatureResourceAccessControl(APIBaseTest):format="json",)self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+++class TestComingSoonWaitlistSurvey(APIBaseTest):+ def _concept_feature(self, name: str = "Sloppy joes") -> EarlyAccessFeature:+ flag = FeatureFlag.objects.create(team=self.team, key=name.lower().replace(" ", "-"), created_by=self.user)+ return EarlyAccessFeature.objects.create(+ team=self.team,+ name=name,+ stage=EarlyAccessFeature.Stage.CONCEPT,+ feature_flag=flag,+ )++ def test_ensure_creates_api_survey_linked_to_flag_and_sets_payload(self):+ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature()+ survey = ensure_waitlist_survey_for_feature(feature)++ assert survey is not None+ assert survey.type == Survey.SurveyType.API+ assert survey.linked_flag_id == feature.feature_flag_id+ assert survey.questions and survey.questions[0]["type"] == "open"+ question_id = survey.questions[0]["id"]++ feature.refresh_from_db()+ assert feature.payload["survey_id"] == str(survey.id)+ assert feature.payload["survey_question_id"] == question_id++ def test_ensure_is_idempotent(self):+ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature()+ first = ensure_waitlist_survey_for_feature(feature)+ feature.refresh_from_db()+ second = ensure_waitlist_survey_for_feature(feature)++ assert second is None # already has survey_id, nothing to do+ assert Survey.objects.filter(team=self.team, linked_flag=feature.feature_flag).count() == 1+ assert first is not None++ def test_ensure_skips_non_concept_features(self):+ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature(name="Beta thing")+ feature.stage = EarlyAccessFeature.Stage.BETA+ feature.save()++ assert ensure_waitlist_survey_for_feature(feature) is None+ assert Survey.objects.filter(team=self.team).count() == 0++ def test_ensure_appends_flag_key_when_waitlist_name_is_taken(self):+ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ Survey.objects.create(+ team=self.team, name="Sloppy joes waitlist", type=Survey.SurveyType.POPOVER, created_by=self.user+ )+ feature = self._concept_feature(name="Sloppy joes")++ survey = ensure_waitlist_survey_for_feature(feature)++ assert survey is not None+ assert survey.name == "Sloppy joes waitlist (sloppy-joes)"+ assert survey.linked_flag_id == feature.feature_flag_id++ def test_ensure_adopts_survey_created_by_concurrent_task(self):+ # Covers only the adopt-on-IntegrityError control flow: `transaction` is mocked (a+ # TestCase already wraps the whole test in one transaction, so real savepoint and+ # advisory-lock semantics can't be exercised here) and the IntegrityError is raised+ # by the mock, not by a real constraint violation.+ from django.db import IntegrityError++ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature(name="Racy")+ real_create = Survey.objects.create++ def concurrent_create(**kwargs):+ # Simulate another worker winning the race: its survey exists by the time our+ # insert fails on the (team, name) unique constraint.+ real_create(**kwargs)+ raise IntegrityError("duplicate key value violates unique constraint")++ with (+ patch("posthog.tasks.early_access_feature.transaction"),+ patch.object(Survey.objects, "create", side_effect=concurrent_create),+ ):+ survey = ensure_waitlist_survey_for_feature(feature)++ assert survey is not None+ assert Survey.objects.filter(team=self.team, linked_flag=feature.feature_flag).count() == 1+ feature.refresh_from_db()+ assert feature.payload["survey_id"] == str(survey.id)++ def test_ensure_recheck_under_lock_adopts_survey_committed_after_first_check(self):+ # The divergent-name race: the initial linked-survey check misses, another task's+ # survey for the same flag commits before the advisory lock is taken, and without+ # the re-check under the lock this task would create a second survey under the+ # "(flag-key)" suffixed name. Simulate the stale first read and assert the re-check+ # adopts the committed survey instead of creating a duplicate.+ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature(name="Racy")+ existing = Survey.objects.create(+ team=self.team,+ name="Racy waitlist",+ type=Survey.SurveyType.API,+ linked_flag=feature.feature_flag,+ questions=[{"type": "open", "question": "q"}],+ created_by=self.user,+ )++ real_filter = Survey.objects.filter+ first_check = {"done": False}++ def stale_first_read(*args, **kwargs):+ if not first_check["done"]:+ first_check["done"] = True+ return Survey.objects.none()+ return real_filter(*args, **kwargs)++ with patch.object(Survey.objects, "filter", side_effect=stale_first_read):+ survey = ensure_waitlist_survey_for_feature(feature)++ assert survey is not None+ assert survey.id == existing.id+ assert Survey.objects.filter(team=self.team, linked_flag=feature.feature_flag).count() == 1+ feature.refresh_from_db()+ assert feature.payload["survey_id"] == str(existing.id)++ @patch("posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature.delay")+ def test_post_save_enqueues_task_for_concept_feature(self, mock_delay):+ with self.captureOnCommitCallbacks(execute=True):+ feature = self._concept_feature(name="Signal me")++ mock_delay.assert_called_once_with(str(feature.id))++ @parameterized.expand(+ [+ ("beta_stage", EarlyAccessFeature.Stage.BETA, {}),+ ("already_has_survey", EarlyAccessFeature.Stage.CONCEPT, {"survey_id": "some-survey-id"}),+ ]+ )+ @patch("posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature.delay")+ def test_post_save_does_not_enqueue_task(self, _name, stage, payload, mock_delay):+ flag = FeatureFlag.objects.create(team=self.team, key=f"no-enqueue-{_name}", created_by=self.user)+ with self.captureOnCommitCallbacks(execute=True):+ EarlyAccessFeature.objects.create(+ team=self.team, name=f"No enqueue {_name}", stage=stage, feature_flag=flag, payload=payload+ )++ mock_delay.assert_not_called()++ @patch("posthog.tasks.early_access_feature.coming_soon_waitlist_surveys_enabled", return_value=False)+ def test_task_does_nothing_when_flag_disabled(self, _mock_enabled):+ from posthog.tasks.early_access_feature import create_waitlist_survey_for_concept_feature++ feature = self._concept_feature(name="Gated off")+ create_waitlist_survey_for_concept_feature(str(feature.id))++ feature.refresh_from_db()+ assert not (feature.payload or {}).get("survey_id")+ assert Survey.objects.filter(team=self.team).count() == 0++ @patch("posthog.tasks.early_access_feature.coming_soon_waitlist_surveys_enabled", return_value=True)+ def test_task_creates_survey_when_flag_enabled(self, _mock_enabled):+ from posthog.tasks.early_access_feature import create_waitlist_survey_for_concept_feature++ feature = self._concept_feature(name="Gated on")+ create_waitlist_survey_for_concept_feature(str(feature.id))++ feature.refresh_from_db()+ assert feature.payload.get("survey_id")+ assert Survey.objects.filter(team=self.team, linked_flag=feature.feature_flag).count() == 1++ @patch("posthog.tasks.early_access_feature.capture_event")+ @patch("posthog.hogql.query.execute_hogql_query")+ def test_migrate_command_skips_already_responded_emails(self, mock_query, mock_capture):+ from django.core.management import call_command++ from posthog.tasks.early_access_feature import ensure_waitlist_survey_for_feature++ feature = self._concept_feature(name="Migrate me")+ survey = ensure_waitlist_survey_for_feature(feature)+ assert survey is not None++ mock_query.side_effect = [+ # Legacy registrations: one new sign-up, one who already responded (case differs).+ MagicMock(results=[("[email protected]", "did-new"), ("[email protected]", "did-already")]),+ # Emails that already responded to the survey (lowercased by the query).+ MagicMock(results=[("[email protected]",)]),+ ]++ call_command("migrate_enrollments_to_waitlist_surveys", team_id=self.team.id, really_run=True)++ assert mock_capture.call_count == 1+ assert mock_capture.call_args.kwargs["distinct_id"] == "did-new"+ assert mock_capture.call_args.kwargs["properties"]["$survey_response"] == "[email protected]"+ assert mock_capture.call_args.kwargs["properties"]["$survey_id"] == str(survey.id)