: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(wizard): create event definitions from completed plans (#70734)
Fernando Gomes965d403a8092
diff --git a/products/event_definitions/backend/logic/__init__.py b/products/event_definitions/backend/logic/__init__.pynew file mode 100644index 000000000000..e38af6e783c8--- /dev/null+++ b/products/event_definitions/backend/logic/__init__.py@@ -0,0 +1,6 @@+from products.event_definitions.backend.logic.placeholder import (+ PlaceholderEventDefinition,+ create_placeholder_event_definitions,+)++__all__ = ["PlaceholderEventDefinition", "create_placeholder_event_definitions"]diff --git a/products/event_definitions/backend/logic/placeholder.py b/products/event_definitions/backend/logic/placeholder.pynew file mode 100644index 000000000000..dea8dbbfbadf--- /dev/null+++ b/products/event_definitions/backend/logic/placeholder.py@@ -0,0 +1,73 @@+"""Cross-product write helpers for event definitions."""++from collections.abc import Sequence+from dataclasses import dataclass+from typing import TYPE_CHECKING, cast++from django.apps import apps+from django.db.models import Q++from posthog.models import Team+from posthog.settings import EE_AVAILABLE++from products.event_definitions.backend.models import EventDefinition++if TYPE_CHECKING:+ from ee.models.event_definition import EnterpriseEventDefinition+++@dataclass(frozen=True)+class PlaceholderEventDefinition:+ name: str+ description: str | None = None+++def create_placeholder_event_definitions(*, team_id: int, definitions: Sequence[PlaceholderEventDefinition]) -> None:+ """Create event definitions that ingestion can claim when the events are first seen."""+ if not definitions:+ return++ project_id = Team.objects.values_list("project_id", flat=True).get(id=team_id)+ names = [definition.name for definition in definitions]+ event_definitions_by_name = {+ event_definition.name: event_definition+ for event_definition in EventDefinition.objects.filter(+ Q(project_id=project_id) | Q(project_id__isnull=True, team_id=project_id),+ name__in=names,+ )+ }++ for definition in definitions:+ if definition.name in event_definitions_by_name:+ continue+ event_definition, _ = EventDefinition.objects.get_or_create(+ project_id=project_id,+ name=definition.name,+ defaults={"team_id": team_id, "created_at": None, "last_seen_at": None},+ )+ event_definitions_by_name[definition.name] = event_definition++ if not EE_AVAILABLE:+ return++ enterprise_model = cast(type["EnterpriseEventDefinition"], apps.get_model("ee", "EnterpriseEventDefinition"))+ enterprise_events_by_id = enterprise_model.objects.filter(+ pk__in=[event_definition.pk for event_definition in event_definitions_by_name.values()]+ ).in_bulk()++ for definition in definitions:+ event_definition = event_definitions_by_name[definition.name]+ enterprise_event = enterprise_events_by_id.get(event_definition.pk)+ if enterprise_event:+ if definition.description and not enterprise_event.description:+ enterprise_event.description = definition.description+ enterprise_event.save(update_fields=["description", "updated_at"])+ continue++ enterprise_event = enterprise_model(+ eventdefinition_ptr_id=event_definition.id,+ description=definition.description or "",+ )+ enterprise_event.__dict__.update(event_definition.__dict__)+ enterprise_event.description = definition.description or ""+ enterprise_event.save()diff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions.pyindex 50eaf773026c..a98160efab48 100644--- a/products/wizard/backend/logic/sessions.py+++ b/products/wizard/backend/logic/sessions.py@@ -2,54 +2,82 @@Business logic for Wizard sessions."""+import logging+from functools import partial++from django.db import transaction+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO, WizardTaskDTOfrom products.wizard.backend.facade.enums import RunPhase, TaskStatusfrom products.wizard.backend.logic.pubsub import publish_session_updatefrom products.wizard.backend.logic.utils import is_stalefrom products.wizard.backend.metrics import report_session_upsertedfrom products.wizard.backend.models import WizardSession+from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions++logger = logging.getLogger(__name__)def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:"""Upsert a session row and return (dto, created).- `defaults=` is applied on both insert AND update — each push is a full- replacement of `tasks` / `run_phase` / `event_plan` / `error` (matches- the RFC's "each push is the new source of truth"). Concurrent POSTs for- a brand-new session_id can race the unique constraint and surface as a- 500; the CLI's normal HTTP retry handles that on the next attempt.+ `defaults=` is applied on both insert AND update — each push replaces+ `tasks` / `run_phase` / `event_plan` / `error`, except that a completed+ push without an event plan preserves the plan from the running session.+ Concurrent POSTs for a brand-new session_id can race the unique constraint+ and surface as a 500; the CLI's normal HTTP retry handles that on the next+ attempt."""- previous_run_phase = (- WizardSession.objects.filter(team_id=params.team_id, session_id=params.session_id)- .values_list("run_phase", flat=True)- .first()- )- instance, created = WizardSession.objects.update_or_create(- team_id=params.team_id,- session_id=params.session_id,- defaults={- "workflow_id": params.workflow_id,- "skill_id": params.skill_id,- "started_at": params.started_at,- "run_phase": params.run_phase.value,- "tasks": [- {- "id": task.id,- "title": task.title,- "status": task.status.value,- }- for task in params.tasks- ],- "event_plan": params.event_plan,- "error": params.error,- },- )- dto = _to_dto(instance)+ with transaction.atomic():+ previous_session = (+ WizardSession.objects.select_for_update()+ .filter(team_id=params.team_id, session_id=params.session_id)+ .first()+ )+ previous_run_phase = previous_session.run_phase if previous_session else None+ event_plan = params.event_plan+ if event_plan is None and params.run_phase == RunPhase.COMPLETED and previous_session:+ event_plan = previous_session.event_plan++ instance, created = WizardSession.objects.update_or_create(+ team_id=params.team_id,+ session_id=params.session_id,+ defaults={+ "workflow_id": params.workflow_id,+ "skill_id": params.skill_id,+ "started_at": params.started_at,+ "run_phase": params.run_phase.value,+ "tasks": [+ {+ "id": task.id,+ "title": task.title,+ "status": task.status.value,+ }+ for task in params.tasks+ ],+ "event_plan": event_plan,+ "error": params.error,+ },+ )+ if previous_run_phase != RunPhase.COMPLETED.value and params.run_phase == RunPhase.COMPLETED:+ transaction.on_commit(+ partial(_enqueue_event_definition_sync, params.team_id, params.session_id),+ robust=True,+ )+ dto = _to_dto(instance)+report_session_upserted(previous_run_phase, dto)publish_session_update(dto)return dto, created+def _enqueue_event_definition_sync(team_id: int, session_id: str) -> None:+ try:+ sync_wizard_event_definitions.delay(team_id, session_id)+ except Exception:+ logger.exception("Failed to enqueue event definition sync for a completed wizard session")++def get_session(team_id: int, session_id: str) -> WizardSessionDTO | None:instance = WizardSession.objects.filter(team_id=team_id, session_id=session_id).first()return _to_dto(instance) if instance else Nonediff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex 7067cdcb7be4..60c8291adfc6 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -6,7 +6,7 @@ returns DTO-shaped responses. No model imports."""import time-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom typing import Anyfrom django.conf import settings@@ -34,6 +34,7 @@ from products.wizard.backend.facade.contracts import (UpsertWizardSessionRequest,WizardSessionDTO,)+from products.wizard.backend.facade.enums import RunPhasefrom products.wizard.backend.presentation.serializers import (UpsertWizardSessionRequestSerializer,WizardSessionSerializer,@@ -128,6 +129,15 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# with the `@action(url_path=...)` detail-vs-action routes.lookup_value_regex = r"(?!(?:stream|latest)$)[^/]+"+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ if (+ self.action == "create"+ and isinstance(request.data, Mapping)+ and request.data.get("run_phase") == RunPhase.COMPLETED.value+ ):+ return ["wizard_session:write", "event_definition:write"]+ return None+def check_permissions(self, request: Request) -> None:try:team_id = self.team_iddiff --git a/products/wizard/backend/tasks/__init__.py b/products/wizard/backend/tasks/__init__.pynew file mode 100644index 000000000000..b0ba1add2138--- /dev/null+++ b/products/wizard/backend/tasks/__init__.py@@ -0,0 +1,3 @@+from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions++__all__ = ["sync_wizard_event_definitions"]diff --git a/products/wizard/backend/tasks/tasks.py b/products/wizard/backend/tasks/tasks.pynew file mode 100644index 000000000000..e1332c8b63e5--- /dev/null+++ b/products/wizard/backend/tasks/tasks.py@@ -0,0 +1,77 @@+import logging+from typing import Any++from celery import shared_task+from celery.app.task import Task++from posthog.celery_queues import CeleryQueue++from products.event_definitions.backend.logic.placeholder import (+ PlaceholderEventDefinition,+ create_placeholder_event_definitions,+)+from products.wizard.backend.facade.enums import RunPhase+from products.wizard.backend.models import WizardSession++logger = logging.getLogger(__name__)++MAX_PLANNED_EVENT_DEFINITIONS = 50+MAX_PLANNED_EVENT_CANDIDATES = 500+MAX_EVENT_NAME_LENGTH = 400+++def _planned_event_definitions(event_plan: dict[str, Any] | None) -> list[PlaceholderEventDefinition]:+ events = event_plan.get("events") if isinstance(event_plan, dict) else None+ if not isinstance(events, list):+ return []++ definitions: list[PlaceholderEventDefinition] = []+ seen_names: set[str] = set()+ for planned_event in events[:MAX_PLANNED_EVENT_CANDIDATES]:+ if not isinstance(planned_event, dict):+ continue++ raw_name = planned_event.get("name")+ if not isinstance(raw_name, str):+ continue+ name = raw_name.strip().replace("\x00", "\ufffd")+ if not name or name.startswith("$") or len(name) > MAX_EVENT_NAME_LENGTH or name in seen_names:+ continue++ description = planned_event.get("description")+ definitions.append(+ PlaceholderEventDefinition(+ name=name,+ description=description.replace("\x00", "\ufffd") if isinstance(description, str) else None,+ )+ )+ seen_names.add(name)+ if len(definitions) == MAX_PLANNED_EVENT_DEFINITIONS:+ break++ return definitions+++@shared_task(+ bind=True,+ ignore_result=True,+ max_retries=5,+ queue=CeleryQueue.DEFAULT.value,+)+def sync_wizard_event_definitions(self: Task, team_id: int, session_id: str) -> None:+ try:+ session = WizardSession.objects.for_team(team_id).filter(session_id=session_id).first()+ if session is None or session.run_phase != RunPhase.COMPLETED.value:+ return++ create_placeholder_event_definitions(+ team_id=team_id,+ definitions=_planned_event_definitions(session.event_plan),+ )+ except Exception as error:+ countdown = min(2**self.request.retries, 60)+ logger.warning(+ "Retrying wizard event definition sync",+ extra={"team_id": team_id, "session_id": session_id, "retry": self.request.retries},+ )+ raise self.retry(exc=error, countdown=countdown)diff --git a/products/wizard/backend/tests/test_logic.py b/products/wizard/backend/tests/test_logic.pyindex 821fb7665a6e..2f7bced55caa 100644--- a/products/wizard/backend/tests/test_logic.py+++ b/products/wizard/backend/tests/test_logic.py@@ -1,11 +1,20 @@from datetime import UTC, datetimeimport pytest+from unittest.mock import patch+from django.test import override_settings++from posthog.models import Team++from products.event_definitions.backend.models import EventDefinitionfrom products.wizard.backend.facade import api as wizard_facadefrom products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTOfrom products.wizard.backend.facade.enums import RunPhase, TaskStatusfrom products.wizard.backend.metrics import WIZARD_SESSIONS_FINISHED_TOTAL+from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions++from ee.models.event_definition import EnterpriseEventDefinitiondef _input(team_id: int, **overrides) -> UpsertWizardSessionInput:@@ -37,7 +46,8 @@ def test_upsert_creates_new_session(team):@pytest.mark.django_db-def test_upsert_with_same_session_id_replaces_state(team):+@patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")+def test_upsert_with_same_session_id_replaces_state(_mock_sync, team):_, first_created = wizard_facade.upsert(_input(team.id))assert first_created is True@@ -55,6 +65,165 @@ def test_upsert_with_same_session_id_replaces_state(team):assert len(wizard_facade.list_for_team(team.id, limit=100)) == 1+@override_settings(CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPAGATES=True)+def test_completed_transition_creates_event_definitions_once(team, django_capture_on_commit_callbacks):+ event_plan = {"events": [{"name": "checkout_started", "description": "A checkout was started"}]}+ wizard_facade.upsert(_input(team.id, event_plan=event_plan))++ with django_capture_on_commit_callbacks(execute=True):+ completed_session, _ = wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED))+ wizard_facade.upsert(+ _input(+ team.id,+ run_phase=RunPhase.COMPLETED,+ event_plan={"events": [{"name": "completed_push_only"}]},+ )+ )++ event_definition = EventDefinition.objects.get(team=team, project_id=team.project_id, name="checkout_started")+ assert event_definition.created_at is None+ assert event_definition.last_seen_at is None+ assert completed_session.event_plan == event_plan+ assert EventDefinition.objects.filter(team=team, name="checkout_started").count() == 1+ assert not EventDefinition.objects.filter(name="completed_push_only").exists()+++@override_settings(CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPAGATES=True)+def test_completed_transition_creates_enterprise_description(team, django_capture_on_commit_callbacks):+ with django_capture_on_commit_callbacks(execute=True):+ wizard_facade.upsert(+ _input(+ team.id,+ run_phase=RunPhase.COMPLETED,+ event_plan={"events": [{"name": "subscription_started", "description": "A subscription was started"}]},+ )+ )++ event_definition = EnterpriseEventDefinition.objects.get(+ team=team, project_id=team.project_id, name="subscription_started"+ )+ assert event_definition.description == "A subscription was started"+++@override_settings(CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPAGATES=True)[email protected]("event_name", ["", "$pageview", " $pageview ", "x" * 401])+def test_completed_transition_skips_invalid_event_names(team, django_capture_on_commit_callbacks, event_name):+ with django_capture_on_commit_callbacks(execute=True):+ wizard_facade.upsert(+ _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": event_name}]})+ )++ assert not EventDefinition.objects.filter(team=team).exists()+++@override_settings(CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPAGATES=True)+def test_completed_transition_caps_valid_unique_event_definitions(team, django_capture_on_commit_callbacks):+ invalid_and_duplicate_events = [{"name": ""} for _ in range(50)] + [+ {"name": " planned_event_0 "},+ {"name": "planned_event_0"},+ ]+ with django_capture_on_commit_callbacks(execute=True):+ wizard_facade.upsert(+ _input(+ team.id,+ run_phase=RunPhase.COMPLETED,+ event_plan={+ "events": invalid_and_duplicate_events + [{"name": f"planned_event_{index}"} for index in range(51)]+ },+ )+ )++ assert EventDefinition.objects.filter(team=team).count() == 50+ assert EventDefinition.objects.filter(team=team, name="planned_event_0").count() == 1+ assert not EventDefinition.objects.filter(team=team, name="planned_event_50").exists()+++@patch(+ "products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay",+ side_effect=RuntimeError("task dispatch failed"),+)+def test_event_definition_dispatch_failure_does_not_break_completed_upsert(+ _mock_sync, team, django_capture_on_commit_callbacks+):+ with django_capture_on_commit_callbacks(execute=True):+ session, created = wizard_facade.upsert(+ _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": "checkout_started"}]})+ )++ assert created is True+ assert session.run_phase == RunPhase.COMPLETED+++def test_event_definition_task_recovers_after_transient_failure(team):+ with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):+ session, _ = wizard_facade.upsert(+ _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": "checkout_started"}]})+ )++ with (+ patch(+ "products.wizard.backend.tasks.tasks.create_placeholder_event_definitions",+ side_effect=RuntimeError("definition write failed"),+ ),+ pytest.raises(RuntimeError, match="definition write failed"),+ ):+ sync_wizard_event_definitions.run(team.id, session.session_id)++ sync_wizard_event_definitions.run(team.id, session.session_id)++ assert EventDefinition.objects.filter(team=team, name="checkout_started").exists()+++def test_event_definition_task_uses_latest_completed_session_state(team):+ with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):+ session, _ = wizard_facade.upsert(+ _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": "stale_completed_plan"}]})+ )+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING, event_plan=None))++ sync_wizard_event_definitions.run(team.id, session.session_id)++ assert not EventDefinition.objects.filter(team=team, name="stale_completed_plan").exists()++[email protected]("is_legacy", [False, True])+def test_event_definition_task_reuses_definition_from_sibling_environment(team, is_legacy):+ sibling_team = Team.objects.create(+ organization=team.organization,+ project=team.project,+ name="Sibling environment",+ )+ existing_definition = EventDefinition.objects.create(+ team=team,+ project=None if is_legacy else team.project,+ name="checkout_started",+ created_at=None,+ last_seen_at=None,+ )+ with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):+ session, _ = wizard_facade.upsert(+ _input(+ sibling_team.id,+ run_phase=RunPhase.COMPLETED,+ event_plan={"events": [{"name": "checkout_started", "description": "A checkout was started"}]},+ )+ )++ sync_wizard_event_definitions.run(sibling_team.id, session.session_id)++ assert EventDefinition.objects.filter(name="checkout_started").count() == 1+ enterprise_definition = EnterpriseEventDefinition.objects.get(pk=existing_definition.pk)+ assert enterprise_definition.description == "A checkout was started"++@pytest.mark.django_dbdef test_upsert_with_different_session_id_creates_new_row(team):wizard_facade.upsert(_input(team.id, session_id="run-1"))@@ -138,7 +307,8 @@ def test_list_for_team_returns_sessions_ordered_by_started_at_desc(team):@pytest.mark.django_db-def test_upsert_counts_a_terminal_transition_exactly_once(team):+@patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")+def test_upsert_counts_a_terminal_transition_exactly_once(_mock_sync, team):counter = WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow="other", outcome="completed")before = counter._value.get()diff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.pyindex e5cd91634ca7..45dc13ea7cbe 100644--- a/products/wizard/backend/tests/test_presentation.py+++ b/products/wizard/backend/tests/test_presentation.py@@ -4,7 +4,8 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Organization+from posthog.models import Organization, PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.wizard.backend.models import WizardSessionfrom products.wizard.backend.presentation.views import _wizard_sync_killswitch_enabled@@ -37,6 +38,17 @@ class TestWizardSessionViewSet(APIBaseTest):payload.update(overrides)return payload+ def _authenticate_personal_api_key(self, scopes: list[str]) -> None:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Wizard test key",+ user=self.user,+ secure_value=hash_key_value(token),+ scopes=scopes,+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+def test_create_session(self):response = self.client.post(self._url(), self._payload(), format="json")@@ -52,7 +64,42 @@ class TestWizardSessionViewSet(APIBaseTest):self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)- def test_repost_same_session_id_upserts(self):+ def test_completed_session_requires_event_definition_write_scope(self):+ self._authenticate_personal_api_key(["wizard_session:write"])++ response = self.client.post(+ self._url(),+ self._payload(run_phase="completed"),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_running_session_accepts_wizard_write_scope(self):+ self._authenticate_personal_api_key(["wizard_session:write"])++ response = self.client.post(+ self._url(),+ self._payload(run_phase="running"),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")+ def test_completed_session_accepts_event_definition_write_scope(self, _mock_sync):+ self._authenticate_personal_api_key(["wizard_session:write", "event_definition:write"])++ response = self.client.post(+ self._url(),+ self._payload(run_phase="completed"),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")+ def test_repost_same_session_id_upserts(self, _mock_sync):first = self.client.post(self._url(), self._payload(), format="json")self.assertEqual(first.status_code, status.HTTP_201_CREATED)diff --git a/tach.toml b/tach.tomlindex c493bb6fcc23..8712ed35a8ab 100644--- a/tach.toml+++ b/tach.toml@@ -1033,9 +1033,18 @@ from = [[[modules]]path = "products.wizard"-depends_on = ["posthog"]+depends_on = ["posthog", "products.event_definitions"]layer = "modules"+[[interfaces]]+expose = [+ "backend\\.logic\\.placeholder.*",+ "backend\\.models.*",+]+from = [+ "products.event_definitions",+]+[[interfaces]]expose = ["backend\\.facade.*",