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.

refactor(wizard): package session infrastructure (#91819)

Fernando Gomes1f5e8a3e9c11
diff --git a/products/wizard/backend/logic/sessions/__init__.py b/products/wizard/backend/logic/sessions/__init__.py
new file mode 100644
index 000000000000..d244fee1c6df
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/__init__.py
@@ -0,0 +1,13 @@
+from products.wizard.backend.logic.sessions.lifecycle import (
+ get_latest_session,
+ get_session,
+ list_sessions,
+ upsert_session,
+)
+
+__all__ = [
+ "get_latest_session",
+ "get_session",
+ "list_sessions",
+ "upsert_session",
+]
diff --git a/products/wizard/backend/logic/sessions/config.py b/products/wizard/backend/logic/sessions/config.py
new file mode 100644
index 000000000000..92dd5dac808f
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/config.py
@@ -0,0 +1,4 @@
+from datetime import timedelta
+
+STALE_AFTER = timedelta(minutes=10)
+CHANNEL_PREFIX = "wizard_sessions"
diff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions/lifecycle.py
similarity index 72%
rename from products/wizard/backend/logic/sessions.py
rename to products/wizard/backend/logic/sessions/lifecycle.py
index 242876aed0ed..4ee1086e2be4 100644
--- a/products/wizard/backend/logic/sessions.py
+++ b/products/wizard/backend/logic/sessions/lifecycle.py
@@ -7,16 +7,13 @@ from functools import partial
from django.db import transaction
-from products.wizard.backend.facade.contracts import (
- UpsertWizardSessionInput,
- WizardSessionDTO,
- WizardSessionOwnershipError,
- WizardSessionUserDTO,
- WizardTaskDTO,
-)
-from products.wizard.backend.facade.enums import RunPhase, TaskStatus
-from products.wizard.backend.logic.pubsub import publish_session_update
-from products.wizard.backend.logic.utils import is_stale
+from kombu.exceptions import OperationalError
+
+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO
+from products.wizard.backend.facade.enums import WizardSessionRunPhase
+from products.wizard.backend.facade.errors import WizardSessionOwnershipError
+from products.wizard.backend.logic.sessions.pubsub import publish_session_update
+from products.wizard.backend.logic.sessions.serializers import to_session_dto
from products.wizard.backend.metrics import report_session_upserted
from products.wizard.backend.models import WizardSession
from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions
@@ -54,7 +51,7 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
raise WizardSessionOwnershipError("This wizard session belongs to a different user and can't be updated.")
event_plan = params.event_plan
- if event_plan is None and params.run_phase == RunPhase.COMPLETED and previous_session:
+ if event_plan is None and params.run_phase == WizardSessionRunPhase.COMPLETED and previous_session:
event_plan = previous_session.event_plan
# Monotonic within a session: the doc arrives late in the run, so a push without it
@@ -89,12 +86,15 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
defaults=defaults,
create_defaults={**defaults, "created_by_id": params.created_by_id},
)
- if previous_run_phase != RunPhase.COMPLETED.value and params.run_phase == RunPhase.COMPLETED:
+ if (
+ previous_run_phase != WizardSessionRunPhase.COMPLETED.value
+ and params.run_phase == WizardSessionRunPhase.COMPLETED
+ ):
transaction.on_commit(
partial(_enqueue_event_definition_sync, params.team_id, params.session_id),
robust=True,
)
- dto = _to_dto(instance)
+ dto = to_session_dto(instance)
report_session_upserted(previous_run_phase, dto)
publish_session_update(dto)
@@ -103,14 +103,18 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
def _enqueue_event_definition_sync(team_id: int, session_id: str) -> None:
try:
- sync_wizard_event_definitions.delay(team_id, session_id)
- except Exception:
+ sync_wizard_event_definitions.apply_async(
+ args=(team_id, session_id),
+ retry=True,
+ retry_policy={"max_retries": 3, "interval_start": 0, "interval_step": 1, "interval_max": 5},
+ )
+ except OperationalError:
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.select_related("created_by").filter(team_id=team_id, session_id=session_id).first()
- return _to_dto(instance) if instance else None
+ return to_session_dto(instance) if instance else None
def get_latest_session(team_id: int, workflow_id: str, skill_id: str | None = None) -> WizardSessionDTO | None:
@@ -119,7 +123,7 @@ def get_latest_session(team_id: int, workflow_id: str, skill_id: str | None = No
qs = qs.filter(skill_id=skill_id)
# created_at breaks ties on equal (client-supplied, second-granularity) started_at
instance = qs.order_by("-started_at", "-created_at").first()
- return _to_dto(instance) if instance else None
+ return to_session_dto(instance) if instance else None
def list_sessions(
@@ -147,37 +151,4 @@ def list_sessions(
qs = qs[offset : offset + limit]
elif offset:
qs = qs[offset:]
- return [_to_dto(instance) for instance in qs]
-
-
-def _to_dto(instance: WizardSession) -> WizardSessionDTO:
- run_phase = RunPhase(instance.run_phase)
- created_by = instance.created_by
- return WizardSessionDTO(
- session_id=instance.session_id,
- team_id=instance.team_id,
- workflow_id=instance.workflow_id,
- skill_id=instance.skill_id,
- started_at=instance.started_at,
- run_phase=run_phase,
- is_stale=is_stale(run_phase, instance.updated_at),
- tasks=tuple(
- WizardTaskDTO(
- id=task["id"],
- title=task["title"],
- status=TaskStatus(task["status"]),
- )
- for task in (instance.tasks or [])
- ),
- event_plan=instance.event_plan,
- error=instance.error,
- pending_input=instance.pending_input,
- handoff_text=instance.handoff_text,
- created_by=(
- WizardSessionUserDTO(id=created_by.id, first_name=created_by.first_name, email=created_by.email)
- if created_by is not None
- else None
- ),
- created_at=instance.created_at,
- updated_at=instance.updated_at,
- )
+ return [to_session_dto(instance) for instance in qs]
diff --git a/products/wizard/backend/logic/sessions/pubsub.py b/products/wizard/backend/logic/sessions/pubsub.py
new file mode 100644
index 000000000000..369228df4e06
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/pubsub.py
@@ -0,0 +1,122 @@
+"""
+Redis pub/sub fanout for wizard session updates.
+
+Publish happens inside `transaction.on_commit` so subscribers never see
+uncommitted state. Subscribers (SSE endpoint) use the async client so each
+idle connection is a coroutine on the event loop, not a thread pinning the
+asgiref pool.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from typing import Any
+
+from django.db import transaction
+
+import structlog
+from redis.exceptions import RedisError
+
+from posthog.redis import get_async_client, get_client
+
+from products.wizard.backend.facade.contracts import WizardSessionDTO
+from products.wizard.backend.logic.sessions.config import CHANNEL_PREFIX
+from products.wizard.backend.logic.sessions.serializers import serialize_session_dto
+from products.wizard.backend.logic.sessions.validation import validate_channel_identifier
+from products.wizard.backend.metrics import WIZARD_PUBSUB_PUBLISH_TOTAL
+
+logger = structlog.get_logger(__name__)
+
+
+def channel_name(team_id: int, workflow_id: str, skill_id: str) -> str:
+ validate_channel_identifier(workflow_id, "workflow_id")
+ validate_channel_identifier(skill_id, "skill_id")
+ return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:{skill_id}"
+
+
+def channel_pattern(team_id: int, workflow_id: str) -> str:
+ """Pattern for subscribing to all skills under a (team, workflow_id)."""
+ validate_channel_identifier(workflow_id, "workflow_id")
+ return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:*"
+
+
+def serialize_dto(dto: WizardSessionDTO) -> bytes:
+ return serialize_session_dto(dto)
+
+
+def publish_session_update(dto: WizardSessionDTO) -> None:
+ """Schedule a Redis publish after the current transaction commits.
+
+ Publish failures are logged and swallowed — fanout is best-effort and
+ must not fail the already-committed upsert.
+ """
+ payload = serialize_dto(dto)
+ channel = channel_name(dto.team_id, dto.workflow_id, dto.skill_id)
+
+ def _publish() -> None:
+ try:
+ receivers = get_client().publish(channel, payload)
+ except RedisError:
+ WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="failed").inc()
+ logger.exception(
+ "wizard_sessions publish failed",
+ channel=channel,
+ session_id=dto.session_id,
+ payload_bytes=len(payload),
+ )
+ return
+ WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="published").inc()
+ logger.debug(
+ "wizard_sessions publish",
+ channel=channel,
+ session_id=dto.session_id,
+ run_phase=dto.run_phase.value,
+ payload_bytes=len(payload),
+ receivers=receivers,
+ )
+
+ transaction.on_commit(_publish)
+
+
+@asynccontextmanager
+async def subscribe(team_id: int, workflow_id: str, skill_id: str | None = None) -> AsyncIterator[Any]:
+ """Subscribe to wizard-session events.
+
+ With `skill_id`, subscribes to the exact `(team, workflow, skill)` channel.
+ Without it, pattern-subscribes to every skill under `(team, workflow)`;
+ messages arrive as `{type: 'pmessage', ...}` instead of `{type: 'message'}`.
+ """
+ if skill_id is not None:
+ target = channel_name(team_id, workflow_id, skill_id)
+ is_pattern = False
+ else:
+ target = channel_pattern(team_id, workflow_id)
+ is_pattern = True
+
+ redis = get_async_client()
+ pubsub = redis.pubsub(ignore_subscribe_messages=True)
+ subscribed = False
+
+ try:
+ if is_pattern:
+ await pubsub.psubscribe(target)
+ else:
+ await pubsub.subscribe(target)
+ subscribed = True
+
+ yield pubsub
+ finally:
+ if subscribed:
+ try:
+ if is_pattern:
+ await pubsub.punsubscribe(target)
+ else:
+ await pubsub.unsubscribe(target)
+ except RedisError:
+ logger.warning("wizard_sessions unsubscribe failed", target=target)
+
+ try:
+ await pubsub.close()
+ except RedisError:
+ logger.warning("wizard_sessions pubsub close failed", target=target)
diff --git a/products/wizard/backend/logic/sessions/serializers.py b/products/wizard/backend/logic/sessions/serializers.py
new file mode 100644
index 000000000000..f8a668d92d13
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/serializers.py
@@ -0,0 +1,54 @@
+import dataclasses
+from datetime import datetime
+from enum import Enum
+from typing import Any
+
+import orjson
+
+from products.wizard.backend.facade.contracts import WizardSessionDTO, WizardSessionUserDTO, WizardTaskDTO
+from products.wizard.backend.facade.enums import WizardSessionRunPhase, WizardSessionTaskStatus
+from products.wizard.backend.logic.sessions.staleness import is_stale
+from products.wizard.backend.models import WizardSession
+
+
+def serialize_session_dto(dto: WizardSessionDTO) -> bytes:
+ return orjson.dumps(dto, default=_json_default)
+
+
+def to_session_dto(instance: WizardSession) -> WizardSessionDTO:
+ run_phase = WizardSessionRunPhase(instance.run_phase)
+ created_by = instance.created_by
+ return WizardSessionDTO(
+ session_id=instance.session_id,
+ team_id=instance.team_id,
+ workflow_id=instance.workflow_id,
+ skill_id=instance.skill_id,
+ started_at=instance.started_at,
+ run_phase=run_phase,
+ is_stale=is_stale(run_phase, instance.updated_at),
+ tasks=tuple(
+ WizardTaskDTO(id=task["id"], title=task["title"], status=WizardSessionTaskStatus(task["status"]))
+ for task in (instance.tasks or [])
+ ),
+ event_plan=instance.event_plan,
+ error=instance.error,
+ pending_input=instance.pending_input,
+ handoff_text=instance.handoff_text,
+ created_by=(
+ WizardSessionUserDTO(id=created_by.id, first_name=created_by.first_name, email=created_by.email)
+ if created_by is not None
+ else None
+ ),
+ created_at=instance.created_at,
+ updated_at=instance.updated_at,
+ )
+
+
+def _json_default(value: Any) -> Any:
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
+ return dataclasses.asdict(value)
+ if isinstance(value, Enum):
+ return value.value
+ if isinstance(value, datetime):
+ return value.isoformat()
+ raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
diff --git a/products/wizard/backend/logic/sessions/staleness.py b/products/wizard/backend/logic/sessions/staleness.py
new file mode 100644
index 000000000000..4a94f0a0a17a
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/staleness.py
@@ -0,0 +1,14 @@
+from datetime import datetime, timedelta
+
+from django.utils import timezone
+
+from products.wizard.backend.facade.enums import WizardSessionRunPhase
+from products.wizard.backend.logic.sessions.config import STALE_AFTER
+
+
+def is_stale(run_phase: WizardSessionRunPhase, updated_at: datetime, stale_after: timedelta = STALE_AFTER) -> bool:
+ """Determine if a session is stale based on its last update time."""
+ if run_phase in {WizardSessionRunPhase.COMPLETED, WizardSessionRunPhase.ERROR}:
+ return False
+
+ return timezone.now() - updated_at > stale_after
diff --git a/products/wizard/backend/logic/sessions/validation.py b/products/wizard/backend/logic/sessions/validation.py
new file mode 100644
index 000000000000..41b049b88ac6
--- /dev/null
+++ b/products/wizard/backend/logic/sessions/validation.py
@@ -0,0 +1,8 @@
+import re
+
+_SAFE_CHANNEL_IDENTIFIER = re.compile(r"^[A-Za-z0-9_.\-]{1,255}$")
+
+
+def validate_channel_identifier(value: str, name: str) -> None:
+ if _SAFE_CHANNEL_IDENTIFIER.fullmatch(value) is None:
+ raise ValueError(f"{name} must match {_SAFE_CHANNEL_IDENTIFIER.pattern}; got {value!r}")
diff --git a/products/wizard/backend/presentation/sessions/__init__.py b/products/wizard/backend/presentation/sessions/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/presentation/sessions/config.py b/products/wizard/backend/presentation/sessions/config.py
new file mode 100644
index 000000000000..e5076f211d3c
--- /dev/null
+++ b/products/wizard/backend/presentation/sessions/config.py
@@ -0,0 +1,4 @@
+SSE_HEARTBEAT_INTERVAL_SECONDS = 15.0
+SSE_POLL_TIMEOUT_SECONDS = 1.0
+SSE_MAX_DURATION_SECONDS = 15 * 60
+WIZARD_SYNC_KILLSWITCH_FLAG = "onboarding-wizard-sync-killswitch"
diff --git a/products/wizard/backend/presentation/sessions/serializers.py b/products/wizard/backend/presentation/sessions/serializers.py
new file mode 100644
index 000000000000..efeb1ffa473d
--- /dev/null
+++ b/products/wizard/backend/presentation/sessions/serializers.py
@@ -0,0 +1,183 @@
+"""DRF serializers for wizard. Bound to facade DTOs, not Django models."""
+
+from typing import Any
+
+from rest_framework import serializers
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from products.wizard.backend.facade.contracts import UpsertWizardSessionRequest, WizardSessionDTO
+
+# Bounds on the pending question. A prompt is a terminal question, not a document, and the wizard
+# asks one thing at a time; the caps keep a malformed or hostile push from growing the row that the
+# app-wide widget reads on every page load.
+MAX_PROMPT_LENGTH = 2000
+MAX_PROMPTS = 10
+
+# Bound on the handoff doc. It IS a document (the wizard's setup report, a few KB of markdown in
+# practice), but the row is streamed over SSE and republished on every later upsert, so cap it well
+# below anything a hostile push could use to balloon the channel. The CLI truncates to the same cap.
+MAX_HANDOFF_TEXT_LENGTH = 64 * 1024
+DEFAULT_LIST_LIMIT = 50
+MAX_LIST_LIMIT = 200
+
+
+class WizardSessionListQuerySerializer(serializers.Serializer):
+ workflow_id = serializers.CharField(
+ required=False,
+ help_text="Return sessions for this workflow only.",
+ )
+ skill_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Return sessions for this skill only.",
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ help_text="Number of sessions to skip.",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=DEFAULT_LIST_LIMIT,
+ min_value=0,
+ max_value=MAX_LIST_LIMIT,
+ help_text="Maximum number of sessions to return.",
+ )
+
+
+class WizardSessionLookupQuerySerializer(serializers.Serializer):
+ workflow_id = serializers.CharField(
+ required=True,
+ help_text="Workflow to inspect.",
+ )
+ skill_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Optional skill within the workflow.",
+ )
+
+
+class PendingInputSerializer(serializers.Serializer):
+ """The in-flight `wizard_ask` question. Typed rather than a free-form dict so the shape the
+ widget renders is enforced at the edge instead of trusted from the producer."""
+
+ id = serializers.CharField(
+ max_length=255,
+ help_text="Identifier the wizard mints for this question. Changes when a new question is asked.",
+ )
+ asked_at = serializers.DateTimeField(
+ required=False,
+ help_text="UTC timestamp when the wizard asked. Defaults to the session's update time when absent.",
+ )
+ question_count = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=100,
+ help_text="How many questions this single ask covers.",
+ )
+ sensitive = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Whether the answer is a secret. Sensitive questions never carry prompt text.",
+ )
+ prompts = serializers.ListField(
+ required=False,
+ max_length=MAX_PROMPTS,
+ child=serializers.CharField(max_length=MAX_PROMPT_LENGTH, allow_blank=True),
+ help_text="The question text shown to the user. Always empty for sensitive questions.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # Redact here rather than in the client: the sensitive contract has to hold for every
+ # producer, and past this point the value is persisted, streamed over SSE, and logged.
+ if attrs.get("sensitive"):
+ attrs.pop("prompts", None)
+ asked_at = attrs.get("asked_at")
+ if asked_at is not None:
+ # The field is a JSONField on the model, which can't hold a datetime.
+ attrs["asked_at"] = asked_at.isoformat()
+ return attrs
+
+
+class WizardSessionSerializer(DataclassSerializer):
+ """Output: serialises a WizardSessionDTO returned by the facade."""
+
+ pending_input = PendingInputSerializer(
+ allow_null=True,
+ help_text="The question the wizard is currently blocked on, or null when nothing is pending.",
+ )
+
+ class Meta:
+ dataclass = WizardSessionDTO
+ extra_kwargs = {
+ "created_by": {
+ "help_text": (
+ "The user who initiated this wizard run (null for runs created before attribution existed)."
+ ),
+ },
+ "handoff_text": {
+ "help_text": (
+ "Markdown handoff doc the wizard produced for this run (its setup report), "
+ "or null while the run hasn't written one."
+ ),
+ },
+ }
+
+
+class UpsertWizardSessionRequestSerializer(DataclassSerializer):
+ """Input: validates the JSON the wizard CLI posts. team_id is derived from URL."""
+
+ pending_input = PendingInputSerializer(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Populated while the wizard is blocked on a question in the terminal. "
+ "Null/absent means no input is pending; a push without it clears the previous prompt."
+ ),
+ )
+ # trim_whitespace would mangle markdown that opens with indentation (e.g. a code block).
+ handoff_text = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ trim_whitespace=False,
+ max_length=MAX_HANDOFF_TEXT_LENGTH,
+ help_text=(
+ "Markdown handoff doc for the run (the wizard's setup report). Send it once the run "
+ "has produced one; omitting it on later pushes keeps the stored value."
+ ),
+ )
+
+ class Meta:
+ dataclass = UpsertWizardSessionRequest
+ extra_kwargs = {
+ "session_id": {
+ "max_length": 255,
+ "help_text": (
+ "Stable identifier the wizard mints for this run "
+ "(format: '{workflow_id}-{skill_id}-{started_at_iso}'). "
+ "Reposting with the same session_id upserts the existing row."
+ ),
+ },
+ "workflow_id": {
+ "max_length": 255,
+ "help_text": "High-level workflow being run, e.g. 'onboarding', 'migration', 'audit'.",
+ },
+ "skill_id": {
+ "max_length": 255,
+ "help_text": "Specific skill within the workflow, e.g. 'nextjs', 'django', 'laravel'.",
+ },
+ "started_at": {
+ "help_text": "UTC timestamp when the wizard started this run. Matches the timestamp encoded in session_id.",
+ },
+ "run_phase": {
+ "help_text": "Lifecycle stage of the wizard run.",
+ },
+ "event_plan": {
+ "help_text": "Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.",
+ },
+ "error": {
+ "help_text": "Populated when run_phase='error'. Shape: { type: string, message: string }.",
+ },
+ }
diff --git a/products/wizard/backend/presentation/sessions/views.py b/products/wizard/backend/presentation/sessions/views.py
new file mode 100644
index 000000000000..b371746eecd1
--- /dev/null
+++ b/products/wizard/backend/presentation/sessions/views.py
@@ -0,0 +1,374 @@
+"""
+DRF views for wizard.
+
+Validates JSON via serializers, routes everything through the facade,
+returns DTO-shaped responses. No model imports.
+"""
+
+import time
+from collections.abc import AsyncIterator, Mapping
+from typing import Any
+
+from django.conf import settings
+from django.http import HttpResponse
+from django.http.response import HttpResponseBase
+
+import structlog
+import posthoganalytics
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.renderers import BaseRenderer
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.streaming import sse_streaming_response
+from posthog.models.scoping import team_scope
+from posthog.sync import database_sync_to_async
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import (
+ UpsertWizardSessionInput,
+ UpsertWizardSessionRequest,
+ WizardSessionDTO,
+)
+from products.wizard.backend.facade.enums import WizardSessionRunPhase
+from products.wizard.backend.facade.errors import WizardSessionOwnershipError
+from products.wizard.backend.presentation.sessions import config as session_config
+from products.wizard.backend.presentation.sessions.serializers import (
+ UpsertWizardSessionRequestSerializer,
+ WizardSessionListQuerySerializer,
+ WizardSessionLookupQuerySerializer,
+ WizardSessionSerializer,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+class EventStreamRenderer(BaseRenderer):
+ """Satisfies DRF content negotiation for `Accept: text/event-stream`; never actually invoked."""
+
+ media_type = "text/event-stream"
+ format = "event-stream"
+ charset = "utf-8"
+
+ def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:
+ return data if isinstance(data, bytes) else b""
+
+
+def _log_request_auth(request: Request, *, action: str, team_id: int | None) -> None:
+ if not logger.isEnabledFor(10): # logging.DEBUG
+ return
+
+ authenticator = getattr(request, "successful_authenticator", None)
+ auth_type = type(authenticator).__name__ if authenticator else "Anonymous"
+ user = getattr(request, "user", None)
+ user_id = getattr(user, "id", None) if user and not user.is_anonymous else None
+
+ scopes: list[str] = []
+ scoped_teams: list[int] = []
+ scoped_organizations: list[str] = []
+
+ pak = getattr(authenticator, "personal_api_key", None)
+ if pak is not None:
+ scopes = list(pak.scopes or [])
+ scoped_teams = list(pak.scoped_teams or [])
+ scoped_organizations = list(pak.scoped_organizations or [])
+
+ token = getattr(authenticator, "access_token", None)
+ if token is not None:
+ scope_str: str = getattr(token, "scope", "") or ""
+ scopes = list(scope_str.split())
+ scoped_teams = list(getattr(token, "scoped_teams", None) or [])
+ scoped_organizations = list(getattr(token, "scoped_organizations", None) or [])
+
+ logger.debug(
+ "wizard_sessions request",
+ action=action,
+ method=request.method,
+ path=request.path,
+ team_id_from_url=team_id,
+ auth_type=auth_type,
+ user_id=user_id,
+ scopes=scopes,
+ scoped_teams=scoped_teams,
+ scoped_organizations=scoped_organizations,
+ )
+
+
+def _wizard_sync_killswitch_enabled(distinct_id: str) -> bool:
+ # Local-only eval: no per-request network/decide call on this hot endpoint.
+ # Flag definitions are served via HyperCache (posthog/apps.py). Fail-open:
+ # if the flag can't be evaluated locally, the stream behaves normally.
+ return bool(
+ posthoganalytics.feature_enabled(
+ session_config.WIZARD_SYNC_KILLSWITCH_FLAG,
+ distinct_id,
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+
+
+class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "wizard_session"
+ scope_object_read_actions = ["list", "retrieve", "stream", "latest"]
+ scope_object_write_actions = ["create"]
+ http_method_names = ["get", "post", "head", "options"]
+ lookup_field = "session_id"
+ # Negative lookahead so a session_id of `stream` or `latest` can't collide
+ # 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") == WizardSessionRunPhase.COMPLETED.value
+ ):
+ return ["wizard_session:write", "event_definition:write"]
+ return None
+
+ def check_permissions(self, request: Request) -> None:
+ try:
+ team_id = self.team_id
+ except (KeyError, ValidationError, NotFound, AttributeError):
+ team_id = None
+ _log_request_auth(request, action=getattr(self, "action", "<unknown>"), team_id=team_id)
+ super().check_permissions(request)
+
+ @extend_schema(
+ description=(
+ "List wizard sessions for the project, ordered by started_at desc. "
+ "This should only be called by the PostHog Wizard. "
+ "Optional filters: ?workflow_id=<id> and ?skill_id=<id>."
+ ),
+ parameters=[WizardSessionListQuerySerializer],
+ responses={200: WizardSessionSerializer(many=True)},
+ )
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # GET /projects/:projectId/wizard/sessions
+ query = WizardSessionListQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ sessions = wizard_facade.list_for_team(
+ self.team_id,
+ workflow_id=query.validated_data.get("workflow_id"),
+ skill_id=query.validated_data.get("skill_id") or None,
+ offset=query.validated_data["offset"],
+ limit=query.validated_data["limit"],
+ )
+ page = self.paginate_queryset(sessions)
+ if page is not None:
+ return self.get_paginated_response(WizardSessionSerializer(page, many=True).data)
+ return Response(WizardSessionSerializer(sessions, many=True).data)
+
+ @extend_schema(
+ description="Retrieve a single wizard session by its session_id.",
+ responses={
+ 200: WizardSessionSerializer,
+ 404: OpenApiResponse(description="No session with that id for this project."),
+ },
+ )
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # GET /projects/:projectId/wizard/sessions/:sessionId
+ session_id = kwargs.get("session_id")
+ if not session_id:
+ return Response({"detail": "session_id is required."}, status=status.HTTP_400_BAD_REQUEST)
+ dto = wizard_facade.get(self.team_id, session_id)
+ if dto is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(WizardSessionSerializer(dto).data)
+
+ def _killswitch_active(self, request: Request) -> bool:
+ # Shared by `latest` and `stream` so flipping the incident flag quiets both the
+ # SSE stream and the 60s REST poll — otherwise the fleet keeps hitting `latest`.
+ user = getattr(request, "user", None)
+ distinct_id = (
+ str(user.distinct_id)
+ if user is not None and not user.is_anonymous and getattr(user, "distinct_id", None)
+ else f"team:{self.team_id}"
+ )
+ return _wizard_sync_killswitch_enabled(distinct_id)
+
+ @extend_schema(
+ description=(
+ "Return the single most-recent wizard session for a workflow (and "
+ "optional skill), or 204 if none exists. Unlike `list`, this is a "
+ "point lookup the app shell uses to decide whether to open the live "
+ "SSE stream — it never returns a collection, and 'no run' is a 204 "
+ "rather than a 404 so clients don't conflate it with a missing "
+ "endpoint."
+ ),
+ parameters=[WizardSessionLookupQuerySerializer],
+ responses={
+ 200: WizardSessionSerializer,
+ 204: OpenApiResponse(description="No session for this workflow/skill in this project."),
+ },
+ )
+ @action(detail=False, methods=["get"], url_path="latest")
+ def latest(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # GET /projects/:projectId/wizard/sessions/latest
+ # Killswitch parity with `stream`: a 204 makes the client treat this as "no run"
+ # and wind the detector down, so flipping the flag in an incident also stops the
+ # 60s poll (and skips the DB read entirely), not just the SSE stream.
+ poll_source = request.headers.get("X-Wizard-Poll-Source")
+ if self._killswitch_active(request):
+ wizard_facade.record_latest_session_poll(poll_source, "killswitch")
+ return Response(status=status.HTTP_204_NO_CONTENT)
+ query = WizardSessionLookupQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ dto = wizard_facade.get_latest(
+ self.team_id,
+ query.validated_data["workflow_id"],
+ query.validated_data.get("skill_id") or None,
+ )
+ if dto is None:
+ wizard_facade.record_latest_session_poll(poll_source, "empty")
+ return Response(status=status.HTTP_204_NO_CONTENT)
+ wizard_facade.record_latest_session_poll(poll_source, "hit")
+ return Response(WizardSessionSerializer(dto).data)
+
+ @extend_schema(
+ description=(
+ "Upsert a wizard session. The `session_id` key is the idempotency anchor — "
+ "reposting the same `session_id` replaces the existing row. Returns 201 on "
+ "create, 200 on update."
+ ),
+ request=UpsertWizardSessionRequestSerializer,
+ responses={
+ 200: WizardSessionSerializer,
+ 201: WizardSessionSerializer,
+ 403: OpenApiResponse(description="The session belongs to a different user."),
+ },
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # POST /projects/:projectId/wizard/sessions
+ serializer = UpsertWizardSessionRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ req: UpsertWizardSessionRequest = serializer.save()
+
+ user = getattr(request, "user", None)
+ created_by_id = user.id if user is not None and not user.is_anonymous else None
+
+ try:
+ dto, created = wizard_facade.upsert(
+ UpsertWizardSessionInput(
+ team_id=self.team_id,
+ session_id=req.session_id,
+ workflow_id=req.workflow_id,
+ skill_id=req.skill_id,
+ started_at=req.started_at,
+ run_phase=req.run_phase,
+ tasks=tuple(req.tasks),
+ event_plan=req.event_plan,
+ error=req.error,
+ pending_input=req.pending_input,
+ handoff_text=req.handoff_text,
+ created_by_id=created_by_id,
+ )
+ )
+ except WizardSessionOwnershipError:
+ raise PermissionDenied("This wizard session belongs to a different user.")
+ response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
+ return Response(WizardSessionSerializer(dto).data, status=response_status)
+
+ @extend_schema(
+ description=(
+ "Server-Sent Events stream of wizard session updates for a "
+ "(workflow_id, skill_id) pair. On connect, the current latest "
+ "session (if any) is emitted as the first event; subsequent "
+ "upserts are streamed in real time. The server closes the "
+ f"connection after {session_config.SSE_MAX_DURATION_SECONDS} seconds with an "
+ "`event: end` line so the client (EventSource) can reconnect.\n\n"
+ "**SDK consumers**: do not call the generated fetch wrapper for "
+ "this path — it will buffer the entire infinite stream. Use the "
+ "URL builder (`getWizardSessionsStreamRetrieveUrl`) with the "
+ "browser's `EventSource` API instead."
+ ),
+ parameters=[WizardSessionLookupQuerySerializer],
+ responses={
+ (200, "text/event-stream"): {
+ "type": "string",
+ "description": "SSE stream of WizardSession events.",
+ }
+ },
+ )
+ @action(detail=False, methods=["get"], url_path="stream", renderer_classes=[EventStreamRenderer])
+ def stream(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
+ # GET /projects/:projectId/wizard/sessions/stream
+ # Killswitch first, before any other work: a 204 tells EventSource to stop
+ # reconnecting, severing the self-reconnect loop for already-open tabs.
+ if self._killswitch_active(request):
+ return HttpResponse(status=204)
+
+ query = WizardSessionLookupQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ workflow_id = query.validated_data["workflow_id"]
+ skill_id = query.validated_data.get("skill_id") or None
+
+ # The generator is `async def` — WSGI can't consume an async iterator.
+ if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":
+ raise RuntimeError("wizard_sessions.stream requires ASGI.")
+
+ generator = _wizard_session_event_stream(
+ team_id=self.team_id,
+ workflow_id=workflow_id,
+ skill_id=skill_id,
+ request=request,
+ )
+ # Releases the request-thread DB connection (auth, team resolution) before
+ # the long-lived stream begins — see sse_streaming_response.
+ return sse_streaming_response(generator, endpoint="wizard_session")
+
+
+async def _wizard_session_event_stream(
+ team_id: int,
+ workflow_id: str,
+ skill_id: str | None,
+ request: Request | None = None,
+) -> AsyncIterator[bytes]:
+ """Stream SSE bytes for a wizard session subscription.
+
+ Subscribes first, then fetches initial state, so publishes that race the
+ snapshot are buffered on the pubsub socket and drained on the next tick.
+ """
+ started_at = time.monotonic()
+
+ async with wizard_facade.subscribe_to_updates(team_id, workflow_id, skill_id) as pubsub:
+
+ def _get_initial() -> WizardSessionDTO | None:
+ with team_scope(team_id):
+ return wizard_facade.get_latest(team_id, workflow_id, skill_id)
+
+ # database_sync_to_async releases the DB connection after the read so it
+ # isn't pinned for the whole SSE stream (CONN_MAX_AGE=0; loop is Redis-only).
+ latest = await database_sync_to_async(_get_initial, thread_sensitive=False)()
+ if latest is not None:
+ yield b"data: " + wizard_facade.serialize_dto(latest) + b"\n\n"
+
+ last_heartbeat = time.monotonic()
+ while True:
+ if time.monotonic() - started_at >= session_config.SSE_MAX_DURATION_SECONDS:
+ yield b"event: end\ndata: reconnect\n\n"
+ return
+
+ if request is not None:
+ is_disconnected = getattr(request, "is_disconnected", None)
+ if is_disconnected is not None:
+ if await is_disconnected():
+ return
+
+ message = await pubsub.get_message(timeout=session_config.SSE_POLL_TIMEOUT_SECONDS)
+ now = time.monotonic()
+
+ # `pmessage` arrives via pattern subscribe; `message` via exact.
+ if message and message.get("type") in ("message", "pmessage"):
+ yield b"data: " + message["data"] + b"\n\n"
+ last_heartbeat = now
+ continue
+
+ if now - last_heartbeat >= session_config.SSE_HEARTBEAT_INTERVAL_SECONDS:
+ yield b": ping\n\n"
+ last_heartbeat = now
diff --git a/products/wizard/backend/tests/sessions/__init__.py b/products/wizard/backend/tests/sessions/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/tests/test_logic.py b/products/wizard/backend/tests/sessions/test_logic.py
similarity index 75%
rename from products/wizard/backend/tests/test_logic.py
rename to products/wizard/backend/tests/sessions/test_logic.py
index 5d9f5304e306..bca2df2a938d 100644
--- a/products/wizard/backend/tests/test_logic.py
+++ b/products/wizard/backend/tests/sessions/test_logic.py
@@ -3,18 +3,18 @@ from datetime import UTC, datetime
import pytest
from unittest.mock import patch
+from django.db import DatabaseError
from django.test import override_settings
+from kombu.exceptions import OperationalError
+
from posthog.models import Team, User
from products.event_definitions.backend.models import EventDefinition
from products.wizard.backend.facade import api as wizard_facade
-from products.wizard.backend.facade.contracts import (
- UpsertWizardSessionInput,
- WizardSessionOwnershipError,
- WizardTaskDTO,
-)
-from products.wizard.backend.facade.enums import RunPhase, TaskStatus
+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO
+from products.wizard.backend.facade.enums import WizardSessionRunPhase, WizardSessionTaskStatus
+from products.wizard.backend.facade.errors import WizardSessionOwnershipError
from products.wizard.backend.metrics import WIZARD_SESSIONS_FINISHED_TOTAL
from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions
@@ -28,8 +28,8 @@ def _input(team_id: int, **overrides) -> UpsertWizardSessionInput:
"workflow_id": "onboarding",
"skill_id": "nextjs",
"started_at": datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC),
- "run_phase": RunPhase.RUNNING,
- "tasks": (WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.IN_PROGRESS),),
+ "run_phase": WizardSessionRunPhase.RUNNING,
+ "tasks": (WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.IN_PROGRESS),),
"event_plan": None,
"error": None,
"pending_input": None,
@@ -45,9 +45,10 @@ def test_upsert_creates_new_session(team):
assert created is True
assert dto.session_id == "onboarding-nextjs-2026-05-19T10:00:00Z"
assert dto.team_id == team.id
- assert dto.run_phase == RunPhase.RUNNING
+ assert dto.run_phase == WizardSessionRunPhase.RUNNING
assert len(dto.tasks) == 1
- assert dto.tasks[0].status == TaskStatus.IN_PROGRESS
+ assert dto.tasks[0].status == WizardSessionTaskStatus.IN_PROGRESS
+ assert not hasattr(dto, "run_id")
@pytest.mark.django_db
@@ -82,7 +83,7 @@ def test_upsert_handoff_text_survives_pushes_without_it(team):
@pytest.mark.django_db
-@patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")
+@patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
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
@@ -90,14 +91,14 @@ def test_upsert_with_same_session_id_replaces_state(_mock_sync, team):
updated, second_created = wizard_facade.upsert(
_input(
team.id,
- run_phase=RunPhase.COMPLETED,
- tasks=(WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.COMPLETED),),
+ run_phase=WizardSessionRunPhase.COMPLETED,
+ tasks=(WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.COMPLETED),),
)
)
assert second_created is False
- assert updated.run_phase == RunPhase.COMPLETED
- assert updated.tasks[0].status == TaskStatus.COMPLETED
+ assert updated.run_phase == WizardSessionRunPhase.COMPLETED
+ assert updated.tasks[0].status == WizardSessionTaskStatus.COMPLETED
assert len(wizard_facade.list_for_team(team.id, limit=100)) == 1
@@ -108,11 +109,11 @@ def test_completed_transition_creates_event_definitions_once(team, django_captur
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))
+ completed_session, _ = wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.COMPLETED))
wizard_facade.upsert(
_input(
team.id,
- run_phase=RunPhase.COMPLETED,
+ run_phase=WizardSessionRunPhase.COMPLETED,
event_plan={"events": [{"name": "completed_push_only"}]},
)
)
@@ -132,7 +133,7 @@ def test_completed_transition_creates_enterprise_description(team, django_captur
wizard_facade.upsert(
_input(
team.id,
- run_phase=RunPhase.COMPLETED,
+ run_phase=WizardSessionRunPhase.COMPLETED,
event_plan={"events": [{"name": "subscription_started", "description": "A subscription was started"}]},
)
)
@@ -149,7 +150,7 @@ def test_completed_transition_creates_enterprise_description(team, django_captur
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}]})
+ _input(team.id, run_phase=WizardSessionRunPhase.COMPLETED, event_plan={"events": [{"name": event_name}]})
)
assert not EventDefinition.objects.filter(team=team).exists()
@@ -166,7 +167,7 @@ def test_completed_transition_caps_valid_unique_event_definitions(team, django_c
wizard_facade.upsert(
_input(
team.id,
- run_phase=RunPhase.COMPLETED,
+ run_phase=WizardSessionRunPhase.COMPLETED,
event_plan={
"events": invalid_and_duplicate_events + [{"name": f"planned_event_{index}"} for index in range(51)]
},
@@ -180,34 +181,47 @@ def test_completed_transition_caps_valid_unique_event_definitions(team, django_c
@pytest.mark.django_db
@patch(
- "products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay",
- side_effect=RuntimeError("task dispatch failed"),
+ "products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async",
+ side_effect=OperationalError("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"}]})
+ _input(
+ team.id,
+ run_phase=WizardSessionRunPhase.COMPLETED,
+ event_plan={"events": [{"name": "checkout_started"}]},
+ )
)
assert created is True
- assert session.run_phase == RunPhase.COMPLETED
+ assert session.run_phase == WizardSessionRunPhase.COMPLETED
+ _mock_sync.assert_called_once_with(
+ args=(team.id, "onboarding-nextjs-2026-05-19T10:00:00Z"),
+ retry=True,
+ retry_policy={"max_retries": 3, "interval_start": 0, "interval_step": 1, "interval_max": 5},
+ )
@pytest.mark.django_db
def test_event_definition_task_recovers_after_transient_failure(team):
- with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):
+ with patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async"):
session, _ = wizard_facade.upsert(
- _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": "checkout_started"}]})
+ _input(
+ team.id,
+ run_phase=WizardSessionRunPhase.COMPLETED,
+ event_plan={"events": [{"name": "checkout_started"}]},
+ )
)
with (
patch(
"products.wizard.backend.tasks.tasks.create_placeholder_event_definitions",
- side_effect=RuntimeError("definition write failed"),
+ side_effect=DatabaseError("definition write failed"),
),
- pytest.raises(RuntimeError, match="definition write failed"),
+ pytest.raises(DatabaseError, match="definition write failed"),
):
sync_wizard_event_definitions.run(team.id, session.session_id)
@@ -218,11 +232,15 @@ def test_event_definition_task_recovers_after_transient_failure(team):
@pytest.mark.django_db
def test_event_definition_task_uses_latest_completed_session_state(team):
- with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):
+ with patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async"):
session, _ = wizard_facade.upsert(
- _input(team.id, run_phase=RunPhase.COMPLETED, event_plan={"events": [{"name": "stale_completed_plan"}]})
+ _input(
+ team.id,
+ run_phase=WizardSessionRunPhase.COMPLETED,
+ event_plan={"events": [{"name": "stale_completed_plan"}]},
+ )
)
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING, event_plan=None))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.RUNNING, event_plan=None))
sync_wizard_event_definitions.run(team.id, session.session_id)
@@ -244,11 +262,11 @@ def test_event_definition_task_reuses_definition_from_sibling_environment(team,
created_at=None,
last_seen_at=None,
)
- with patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay"):
+ with patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async"):
session, _ = wizard_facade.upsert(
_input(
sibling_team.id,
- run_phase=RunPhase.COMPLETED,
+ run_phase=WizardSessionRunPhase.COMPLETED,
event_plan={"events": [{"name": "checkout_started", "description": "A checkout was started"}]},
)
)
@@ -274,7 +292,9 @@ def test_created_by_is_set_on_create_and_preserved_on_owner_update(team, user):
assert created.created_by is not None
assert created.created_by.id == user.id
- updated, was_created = wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=user.id))
+ updated, was_created = wizard_facade.upsert(
+ _input(team.id, run_phase=WizardSessionRunPhase.COMPLETED, created_by_id=user.id)
+ )
assert was_created is False
assert updated.created_by is not None
assert updated.created_by.id == user.id
@@ -283,15 +303,15 @@ def test_created_by_is_set_on_create_and_preserved_on_owner_update(team, user):
@pytest.mark.django_db
def test_upsert_by_a_different_user_is_rejected(team, user):
other_user = User.objects.create(email="[email protected]", first_name="Second")
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING, created_by_id=user.id))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.RUNNING, created_by_id=user.id))
with pytest.raises(WizardSessionOwnershipError):
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=other_user.id))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.COMPLETED, created_by_id=other_user.id))
# The owner's run data is left untouched.
current = wizard_facade.get(team.id, _input(team.id).session_id)
assert current is not None
- assert current.run_phase == RunPhase.RUNNING
+ assert current.run_phase == WizardSessionRunPhase.RUNNING
assert current.created_by is not None
assert current.created_by.id == user.id
@@ -301,9 +321,11 @@ def test_upsert_allows_update_of_legacy_unattributed_session(team, user):
# Rows created before attribution existed carry a null created_by and stay updatable by anyone.
wizard_facade.upsert(_input(team.id, created_by_id=None))
- updated, was_created = wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=user.id))
+ updated, was_created = wizard_facade.upsert(
+ _input(team.id, run_phase=WizardSessionRunPhase.COMPLETED, created_by_id=user.id)
+ )
assert was_created is False
- assert updated.run_phase == RunPhase.COMPLETED
+ assert updated.run_phase == WizardSessionRunPhase.COMPLETED
@pytest.mark.django_db
@@ -381,14 +403,14 @@ def test_list_for_team_returns_sessions_ordered_by_started_at_desc(team):
@pytest.mark.django_db
-@patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")
+@patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
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()
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING))
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED))
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.RUNNING))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.COMPLETED))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.COMPLETED))
assert counter._value.get() == before + 1
@@ -398,6 +420,6 @@ def test_upsert_counts_a_session_created_already_terminal(team):
counter = WIZARD_SESSIONS_FINISHED_TOTAL.labels(workflow="other", outcome="error")
before = counter._value.get()
- wizard_facade.upsert(_input(team.id, run_phase=RunPhase.ERROR, error={"type": "boom", "message": "x"}))
+ wizard_facade.upsert(_input(team.id, run_phase=WizardSessionRunPhase.ERROR, error={"type": "boom", "message": "x"}))
assert counter._value.get() == before + 1
diff --git a/products/wizard/backend/tests/sessions/test_pubsub.py b/products/wizard/backend/tests/sessions/test_pubsub.py
new file mode 100644
index 000000000000..b19e9b206421
--- /dev/null
+++ b/products/wizard/backend/tests/sessions/test_pubsub.py
@@ -0,0 +1,121 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.db import transaction
+
+from redis.exceptions import ConnectionError as RedisConnectionError
+
+from products.wizard.backend.facade.contracts import WizardSessionDTO, WizardTaskDTO
+from products.wizard.backend.facade.enums import WizardSessionRunPhase, WizardSessionTaskStatus
+from products.wizard.backend.logic.sessions.pubsub import channel_name, publish_session_update, subscribe
+from products.wizard.backend.logic.sessions.validation import validate_channel_identifier
+
+
+def _dto(team_id: int = 1) -> WizardSessionDTO:
+ now = datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC)
+ return WizardSessionDTO(
+ # session_id has no colons because channel_name validates the safe-id
+ # alphabet on workflow_id/skill_id. session_id itself isn't part of
+ # the channel name, but we still keep the format safe for downstream
+ # consumers.
+ session_id="onboarding-nextjs-2026-05-19T10-00-00Z",
+ team_id=team_id,
+ workflow_id="onboarding",
+ skill_id="nextjs",
+ started_at=now,
+ run_phase=WizardSessionRunPhase.RUNNING,
+ is_stale=False,
+ tasks=(WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.IN_PROGRESS),),
+ event_plan=None,
+ error=None,
+ pending_input=None,
+ handoff_text=None,
+ created_by=None,
+ created_at=now,
+ updated_at=now,
+ )
+
+
+def test_channel_name_is_deterministic():
+ assert channel_name(1, "onboarding", "nextjs") == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"
+
+
+def test_channel_name_rejects_unsafe_ids():
+ """workflow_id / skill_id can't smuggle Redis glob metacharacters or `:`."""
+ with pytest.raises(ValueError):
+ channel_name(1, "onboarding", "next*")
+ with pytest.raises(ValueError):
+ channel_name(1, "*", "nextjs")
+ with pytest.raises(ValueError):
+ channel_name(1, "onboarding:malicious", "nextjs")
+ with pytest.raises(ValueError):
+ channel_name(1, "onboarding", "next[js]")
+
+
+def test_channel_identifier_accepts_safe_values() -> None:
+ validate_channel_identifier("onboarding", "workflow_id")
+
+
[email protected]_db(transaction=True)
+def test_publish_session_update_publishes_after_commit():
+ """In transaction.atomic, the publish should defer to on_commit."""
+ redis_mock = MagicMock()
+ with patch("products.wizard.backend.logic.sessions.pubsub.get_client", return_value=redis_mock):
+ with transaction.atomic():
+ publish_session_update(_dto())
+ assert redis_mock.publish.call_count == 0 # not yet committed
+
+ # After atomic block exits, on_commit hooks fire.
+ assert redis_mock.publish.call_count == 1
+ channel, payload = redis_mock.publish.call_args.args
+ assert channel == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"
+ assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in payload
+ assert b'"run_phase":"running"' in payload
+ assert b'"status":"in_progress"' in payload
+
+
+def test_publish_session_update_does_not_publish_on_rollback():
+ redis_mock = MagicMock()
+ with patch("products.wizard.backend.logic.sessions.pubsub.get_client", return_value=redis_mock):
+ try:
+ with transaction.atomic():
+ publish_session_update(_dto())
+ raise RuntimeError("force rollback")
+ except RuntimeError:
+ pass
+
+ assert redis_mock.publish.call_count == 0
+
+
[email protected]_db(transaction=True)
+def test_publish_session_update_swallows_redis_errors():
+ """Redis publish failure must not fail the upsert request."""
+ redis_mock = MagicMock()
+ redis_mock.publish.side_effect = RedisConnectionError("redis is down")
+
+ with patch("products.wizard.backend.logic.sessions.pubsub.get_client", return_value=redis_mock):
+ with transaction.atomic():
+ publish_session_update(_dto())
+ # If the exception escaped on_commit, this assertion wouldn't run.
+ assert redis_mock.publish.call_count == 1
+
+
+async def test_subscribe_closes_pubsub_when_subscription_has_programming_error() -> None:
+ pubsub = MagicMock()
+ pubsub.subscribe = AsyncMock(side_effect=RuntimeError("bug"))
+ pubsub.close = AsyncMock()
+ redis = MagicMock()
+ redis.pubsub.return_value = pubsub
+
+ with (
+ patch("products.wizard.backend.logic.sessions.pubsub.get_async_client", return_value=redis),
+ pytest.raises(RuntimeError, match="bug"),
+ ):
+ async with subscribe(1, "onboarding", "nextjs"):
+ pass
+
+ pubsub.close.assert_awaited_once_with()
diff --git a/products/wizard/backend/tests/sessions/test_session_presentation.py b/products/wizard/backend/tests/sessions/test_session_presentation.py
new file mode 100644
index 000000000000..c505a0c6489f
--- /dev/null
+++ b/products/wizard/backend/tests/sessions/test_session_presentation.py
@@ -0,0 +1,493 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, PersonalAPIKey, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.wizard.backend.models import WizardSession
+from products.wizard.backend.presentation.sessions.serializers import WizardSessionListQuerySerializer
+from products.wizard.backend.presentation.sessions.views import _wizard_sync_killswitch_enabled
+
+
+def test_list_query_rejects_invalid_pagination() -> None:
+ serializer = WizardSessionListQuerySerializer(data={"limit": "invalid"})
+
+ assert not serializer.is_valid()
+ assert serializer.errors["limit"][0].code == "invalid"
+
+
+class TestWizardSessionViewSet(APIBaseTest):
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/wizard/sessions/{suffix}"
+
+ def _payload(self, **overrides) -> dict:
+ payload = {
+ "session_id": "onboarding-nextjs-2026-05-19T10:00:00Z",
+ "workflow_id": "onboarding",
+ "skill_id": "nextjs",
+ "started_at": "2026-05-19T10:00:00Z",
+ "run_phase": "running",
+ "tasks": [
+ {
+ "id": "1",
+ "title": "Install Next.js plugin",
+ "status": "in_progress",
+ },
+ {
+ "id": "2",
+ "title": "Configure plugin with API key",
+ "status": "pending",
+ },
+ ],
+ }
+ 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")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ data = response.json()
+ self.assertEqual(data["session_id"], "onboarding-nextjs-2026-05-19T10:00:00Z")
+ self.assertEqual(data["workflow_id"], "onboarding")
+ self.assertEqual(data["skill_id"], "nextjs")
+ self.assertEqual(data["run_phase"], "running")
+ self.assertEqual(len(data["tasks"]), 2)
+ self.assertEqual(data["team_id"], self.team.id)
+ self.assertNotIn("run_id", data)
+
+ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)
+
+ def test_create_session_attributes_run_to_authenticated_user(self):
+ response = self.client.post(self._url(), self._payload(), format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ created_by = response.json()["created_by"]
+ self.assertEqual(created_by["id"], self.user.id)
+ self.assertEqual(created_by["email"], self.user.email)
+ self.assertEqual(created_by["first_name"], self.user.first_name)
+
+ 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.lifecycle.sync_wizard_event_definitions.apply_async")
+ 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.lifecycle.sync_wizard_event_definitions.apply_async")
+ 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)
+
+ response = self.client.post(
+ self._url(),
+ self._payload(run_phase="completed", tasks=[{"id": "1", "title": "Install SDK", "status": "completed"}]),
+ format="json",
+ )
+
+ # Second POST against the same session_id is an update, not a create.
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ data = response.json()
+ self.assertEqual(data["run_phase"], "completed")
+ self.assertEqual(len(data["tasks"]), 1)
+ self.assertEqual(data["tasks"][0]["status"], "completed")
+
+ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)
+
+ def test_repost_by_a_different_user_is_forbidden(self):
+ first = self.client.post(self._url(), self._payload(), format="json")
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.client.force_login(other_user)
+
+ response = self.client.post(
+ self._url(),
+ self._payload(run_phase="completed"),
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_different_session_id_creates_new_row(self):
+ self.client.post(self._url(), self._payload(), format="json")
+
+ self.client.post(
+ self._url(),
+ self._payload(session_id="onboarding-nextjs-2026-05-19T10:20:39Z"),
+ format="json",
+ )
+
+ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 2)
+
+ def test_list_returns_sessions_ordered_by_started_at_desc(self):
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-2026-05-19T09:00:00Z",
+ started_at="2026-05-19T09:00:00Z",
+ ),
+ format="json",
+ )
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-2026-05-19T19:00:00Z",
+ started_at="2026-05-19T19:00:00Z",
+ ),
+ format="json",
+ )
+
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 2)
+ self.assertEqual(results[0]["started_at"], "2026-05-19T19:00:00Z")
+ self.assertEqual(results[1]["started_at"], "2026-05-19T09:00:00Z")
+
+ def test_list_filters_by_workflow_and_skill(self):
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-1",
+ workflow_id="onboarding",
+ skill_id="nextjs",
+ ),
+ format="json",
+ )
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="migration-amplitude-1",
+ workflow_id="migration",
+ skill_id="amplitude",
+ ),
+ format="json",
+ )
+
+ response = self.client.get(self._url() + "?workflow_id=onboarding")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["workflow_id"], "onboarding")
+
+ response = self.client.get(self._url() + "?workflow_id=onboarding&skill_id=django")
+ self.assertEqual(len(response.json()["results"]), 0)
+
+ def test_list_empty_skill_id_is_ignored(self):
+ # An empty skill_id is treated as no filter, so the session still shows up.
+ self.client.post(
+ self._url(),
+ self._payload(workflow_id="onboarding", skill_id="nextjs"),
+ format="json",
+ )
+
+ response = self.client.get(self._url() + "?workflow_id=onboarding&skill_id=")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 1)
+
+ def test_retrieve_by_session_id(self):
+ self.client.post(self._url(), self._payload(), format="json")
+
+ response = self.client.get(self._url("onboarding-nextjs-2026-05-19T10:00:00Z/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["workflow_id"], "onboarding")
+
+ def test_retrieve_unknown_session_returns_404(self):
+ response = self.client.get(self._url("does-not-exist/"))
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_latest_returns_most_recent_session_for_workflow(self):
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-2026-05-19T09:00:00Z",
+ started_at="2026-05-19T09:00:00Z",
+ ),
+ format="json",
+ )
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-2026-05-19T19:00:00Z",
+ started_at="2026-05-19T19:00:00Z",
+ ),
+ format="json",
+ )
+
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["started_at"], "2026-05-19T19:00:00Z")
+ # A bare object, not a paginated `{results: [...]}` envelope.
+ self.assertNotIn("results", body)
+ self.assertEqual(body["session_id"], "onboarding-nextjs-2026-05-19T19:00:00Z")
+
+ def test_latest_breaks_started_at_ties_by_created_at(self):
+ # Same started_at; the row POSTed second has the later created_at and wins.
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-first",
+ started_at="2026-05-19T10:00:00Z",
+ ),
+ format="json",
+ )
+ self.client.post(
+ self._url(),
+ self._payload(
+ session_id="onboarding-nextjs-second",
+ started_at="2026-05-19T10:00:00Z",
+ ),
+ format="json",
+ )
+
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["session_id"], "onboarding-nextjs-second")
+
+ def test_latest_skill_id_narrows_the_match(self):
+ self.client.post(
+ self._url(),
+ self._payload(session_id="onboarding-nextjs-1", skill_id="nextjs"),
+ format="json",
+ )
+
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding&skill_id=django")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ def test_latest_without_a_session_returns_204_not_404(self):
+ # 204, not 404: the detector treats 404 as a missing endpoint and stops polling.
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(response.content, b"")
+
+ def test_latest_requires_workflow_id(self):
+ response = self.client.get(self._url("latest/"))
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_latest_does_not_collide_with_session_id_lookup(self):
+ # lookup_value_regex excludes "latest", so the action wins over a retrieve
+ # of a session whose id is literally "latest".
+ self.client.post(
+ self._url(),
+ self._payload(session_id="latest", started_at="2026-05-19T10:00:00Z"),
+ format="json",
+ )
+
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ @parameterized.expand([("delete",), ("put",)])
+ def test_disallowed_verb_returns_405(self, method):
+ self.client.post(self._url(), self._payload(), format="json")
+
+ response = getattr(self.client, method)(self._url("onboarding-nextjs-2026-05-19T10:00:00Z/"))
+
+ self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
+
+ @parameterized.expand(
+ [
+ ("invalid_task_status", {"tasks": [{"id": "1", "title": "x", "status": "pizza"}]}),
+ ("invalid_run_phase", {"run_phase": "exploded"}),
+ ]
+ )
+ def test_invalid_enum_payload_rejected(self, _label, payload_overrides):
+ response = self.client.post(self._url(), self._payload(**payload_overrides), format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_other_team_cannot_see_sessions(self):
+ # Create a session in self.team's project.
+ self.client.post(self._url(), self._payload(), format="json")
+
+ # Spin up a separate org + team. The current user is not a member,
+ # so the project endpoint should refuse the request entirely.
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = self.create_team_with_organization(other_org)
+
+ response = self.client.get(f"/api/projects/{other_team.id}/wizard/sessions/")
+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))
+
+ def test_latest_other_team_cannot_see_sessions(self):
+ # Create a session in self.team's project.
+ self.client.post(self._url(), self._payload(), format="json")
+
+ # Spin up a separate org + team. The current user is not a member,
+ # so the project endpoint should refuse the request entirely.
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = self.create_team_with_organization(other_org)
+
+ response = self.client.get(f"/api/projects/{other_team.id}/wizard/sessions/latest/?workflow_id=onboarding")
+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))
+
+ def test_event_plan_and_error_persisted(self):
+ response = self.client.post(
+ self._url(),
+ self._payload(
+ run_phase="error",
+ event_plan={"events": [{"name": "$pageview"}]},
+ error={"type": "TimeoutError", "message": "Anthropic API timed out"},
+ ),
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ data = response.json()
+ self.assertEqual(data["event_plan"], {"events": [{"name": "$pageview"}]})
+ self.assertEqual(data["error"], {"type": "TimeoutError", "message": "Anthropic API timed out"})
+
+ def test_handoff_text_persists_across_pushes_without_it(self):
+ # Leading indentation must survive validation: the doc is markdown, where it is syntax.
+ doc = " indented code block\n\n# Setup report"
+ response = self.client.post(self._url(), self._payload(handoff_text=doc), format="json")
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["handoff_text"], doc)
+
+ response = self.client.post(self._url(), self._payload(), format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["handoff_text"], doc)
+
+ def test_stream_requires_workflow_id(self):
+ # No params → 400 from the view-level validation (workflow_id is the
+ # only required query param; skill_id is optional for pattern subscribe).
+ response = self.client.get(f"{self._url()}stream/")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ @patch("products.wizard.backend.presentation.sessions.views.posthoganalytics.feature_enabled", return_value=True)
+ def test_stream_killswitch_returns_204(self, _mock_feature_enabled):
+ # When the killswitch flag is on, the endpoint short-circuits with a 204
+ # before any stream work — a 204 tells EventSource to stop reconnecting.
+ response = self.client.get(f"{self._url()}stream/?workflow_id=onboarding")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ @patch("products.wizard.backend.presentation.sessions.views.posthoganalytics.feature_enabled", return_value=True)
+ def test_latest_killswitch_returns_204_even_with_a_live_session(self, _mock_feature_enabled):
+ # Parity with stream: with the killswitch on, `latest` short-circuits to a 204
+ # even though a real session exists, so the detector's 60s poll winds down too
+ # (the client treats 204 as "no run") rather than only the SSE stream closing.
+ self.client.post(self._url(), self._payload(), format="json")
+
+ response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ @parameterized.expand([("on", True, True), ("off", False, False), ("unresolved", None, False)])
+ def test_wizard_sync_killswitch_helper(self, _label, flag_value, expected):
+ with patch(
+ "products.wizard.backend.presentation.sessions.views.posthoganalytics.feature_enabled",
+ return_value=flag_value,
+ ):
+ self.assertEqual(_wizard_sync_killswitch_enabled("distinct-id"), expected)
+
+ def test_sensitive_pending_input_is_stored_without_prompt_text(self):
+ # Redaction has to happen before the row is written, since the same value is streamed over
+ # SSE and logged — a client that sends the text anyway must not get it persisted.
+ response = self.client.post(
+ self._url(),
+ self._payload(
+ pending_input={
+ "id": "ask-1",
+ "asked_at": "2026-05-19T10:05:00Z",
+ "question_count": 1,
+ "sensitive": True,
+ "prompts": ["Paste your API key"],
+ }
+ ),
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertNotIn("prompts", response.json()["pending_input"])
+
+ session = WizardSession.objects.unscoped().get(team=self.team)
+ stored = session.pending_input
+ assert stored is not None
+ self.assertNotIn("prompts", stored)
+ self.assertTrue(stored["sensitive"])
+
+ def test_pending_input_with_asked_at_survives_every_read_path(self):
+ # asked_at is validated as a datetime but stored as a string, since the column is JSON.
+ # Every read serializes that string back out through the same DateTimeField.
+ create = self.client.post(
+ self._url(),
+ self._payload(pending_input={"id": "ask-1", "asked_at": "2026-05-19T10:05:00Z"}),
+ format="json",
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED)
+
+ for label, url in [
+ ("latest", self._url("latest/") + "?workflow_id=onboarding"),
+ ("retrieve", self._url("onboarding-nextjs-2026-05-19T10:00:00Z/")),
+ ("list", self._url()),
+ ]:
+ with self.subTest(read=label):
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ payload = body["results"][0] if label == "list" else body
+ self.assertEqual(payload["pending_input"]["id"], "ask-1")
+ self.assertIn("asked_at", payload["pending_input"])
+
+ @parameterized.expand(
+ [
+ ("prompt_not_a_string", {"prompts": [{}]}),
+ ("prompt_too_long", {"prompts": ["x" * 2001]}),
+ ("too_many_prompts", {"prompts": ["q"] * 11}),
+ ("missing_id", {"id": None}),
+ ("question_count_out_of_range", {"question_count": 0}),
+ ]
+ )
+ def test_malformed_pending_input_is_rejected(self, _label, overrides):
+ pending_input = {"id": "ask-1", "sensitive": False, "prompts": ["Which region?"]}
+ pending_input.update(overrides)
+
+ response = self.client.post(self._url(), self._payload(pending_input=pending_input), format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 0)
diff --git a/products/wizard/backend/tests/sessions/test_staleness.py b/products/wizard/backend/tests/sessions/test_staleness.py
new file mode 100644
index 000000000000..371bc8e76889
--- /dev/null
+++ b/products/wizard/backend/tests/sessions/test_staleness.py
@@ -0,0 +1,29 @@
+from datetime import UTC, datetime, timedelta
+
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.wizard.backend.facade.enums import WizardSessionRunPhase
+from products.wizard.backend.logic.sessions.config import STALE_AFTER
+from products.wizard.backend.logic.sessions.staleness import is_stale
+
+_NOW = datetime(2026, 5, 19, 12, 0, 0, tzinfo=UTC)
+
+
+class TestIsStale:
+ @parameterized.expand(
+ [
+ # (label, run_phase, updated_at_offset_from_now, expected)
+ ("running_fresh", WizardSessionRunPhase.RUNNING, timedelta(minutes=1), False),
+ ("running_just_under_threshold", WizardSessionRunPhase.RUNNING, STALE_AFTER - timedelta(seconds=1), False),
+ ("running_just_over_threshold", WizardSessionRunPhase.RUNNING, STALE_AFTER + timedelta(seconds=1), True),
+ ("idle_over_threshold_is_stale", WizardSessionRunPhase.IDLE, STALE_AFTER + timedelta(minutes=5), True),
+ ("completed_never_stale", WizardSessionRunPhase.COMPLETED, STALE_AFTER + timedelta(days=30), False),
+ ("error_never_stale", WizardSessionRunPhase.ERROR, STALE_AFTER + timedelta(days=30), False),
+ ]
+ )
+ def test_is_stale(self, _label: str, run_phase: WizardSessionRunPhase, age: timedelta, expected: bool) -> None:
+ updated_at = _NOW - age
+ with patch("products.wizard.backend.logic.sessions.staleness.timezone.now", return_value=_NOW):
+ assert is_stale(run_phase, updated_at) is expected
diff --git a/products/wizard/backend/tests/sessions/test_stream.py b/products/wizard/backend/tests/sessions/test_stream.py
new file mode 100644
index 000000000000..21666373f38e
--- /dev/null
+++ b/products/wizard/backend/tests/sessions/test_stream.py
@@ -0,0 +1,188 @@
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from asgiref.sync import sync_to_async
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO
+from products.wizard.backend.facade.enums import WizardSessionRunPhase, WizardSessionTaskStatus
+from products.wizard.backend.presentation.sessions.views import _wizard_session_event_stream
+
+
+class _StopStream(Exception):
+ """Helper to break the infinite generator after we've collected what we want."""
+
+
+def _input(team_id: int, **overrides) -> UpsertWizardSessionInput:
+ params: dict = {
+ "team_id": team_id,
+ "session_id": "onboarding-nextjs-2026-05-19T10-00-00Z",
+ "workflow_id": "onboarding",
+ "skill_id": "nextjs",
+ "started_at": datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC),
+ "run_phase": WizardSessionRunPhase.RUNNING,
+ "tasks": (WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.IN_PROGRESS),),
+ "event_plan": None,
+ "error": None,
+ "pending_input": None,
+ }
+ params.update(overrides)
+ return UpsertWizardSessionInput(**params)
+
+
+async def _drain(generator, max_events: int):
+ """Pull up to max_events from the async generator, stopping early on _StopStream."""
+ events = []
+ try:
+ for _ in range(max_events):
+ events.append(await anext(generator))
+ except (_StopStream, StopAsyncIteration):
+ pass
+ finally:
+ # Close the generator so its `async with` runs cleanup (closes the
+ # Redis subscription). Without this, leaked subscriptions would pass
+ # the tests silently.
+ await generator.aclose()
+ return events
+
+
+def _async_subscribe_cm(pubsub_mock):
+ """Build an async context manager that yields the given pubsub mock.
+
+ Tracks enter/exit calls on the returned tuple `(cm_factory, exit_marker)`
+ so tests can assert cleanup ran.
+ """
+ exit_marker = MagicMock(name="exit_marker")
+
+ @asynccontextmanager
+ async def _cm(team_id, workflow_id, skill_id):
+ try:
+ yield pubsub_mock
+ finally:
+ exit_marker(team_id, workflow_id, skill_id)
+
+ return _cm, exit_marker
+
+
+def _patch_subscribe(pubsub_mock):
+ """Patch the facade's `subscribe_to_updates` async context manager.
+
+ Returns the patch object plus a sentinel that records cleanup so tests
+ can confirm the Redis subscription's `__aexit__` ran.
+ """
+ cm_factory, exit_marker = _async_subscribe_cm(pubsub_mock)
+ return (
+ patch(
+ "products.wizard.backend.presentation.sessions.views.wizard_facade.subscribe_to_updates",
+ cm_factory,
+ ),
+ exit_marker,
+ )
+
+
+def _async_get_message(side_effects):
+ return AsyncMock(side_effect=side_effects)
+
+
[email protected]_db(transaction=True)
+async def test_stream_emits_initial_state_when_session_exists(team):
+ await sync_to_async(wizard_facade.upsert)(_input(team.id))
+
+ pubsub_mock = MagicMock()
+ pubsub_mock.get_message = _async_get_message([_StopStream()])
+
+ patcher, exit_marker = _patch_subscribe(pubsub_mock)
+ with patcher:
+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="onboarding", skill_id="nextjs")
+ events = await _drain(gen, max_events=2)
+
+ assert len(events) == 1
+ assert events[0].startswith(b"data: ")
+ assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in events[0]
+ assert events[0].endswith(b"\n\n")
+ # Cleanup must run — otherwise we'd leak Redis subscriptions on every
+ # client disconnect.
+ exit_marker.assert_called_once_with(team.id, "onboarding", "nextjs")
+
+
[email protected]_db(transaction=True)
+async def test_stream_skips_initial_event_when_no_session(team):
+ pubsub_mock = MagicMock()
+ pubsub_mock.get_message = _async_get_message([_StopStream()])
+
+ patcher, exit_marker = _patch_subscribe(pubsub_mock)
+ with patcher:
+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
+ events = await _drain(gen, max_events=2)
+
+ assert events == []
+ exit_marker.assert_called_once()
+
+
[email protected]_db(transaction=True)
+async def test_stream_forwards_pubsub_messages(team):
+ pubsub_mock = MagicMock()
+ pubsub_mock.get_message = _async_get_message(
+ [
+ {"type": "message", "data": b'{"session_id":"a"}'},
+ {"type": "message", "data": b'{"session_id":"b"}'},
+ _StopStream(),
+ ]
+ )
+
+ patcher, exit_marker = _patch_subscribe(pubsub_mock)
+ with patcher:
+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
+ events = await _drain(gen, max_events=5)
+
+ assert events == [
+ b'data: {"session_id":"a"}\n\n',
+ b'data: {"session_id":"b"}\n\n',
+ ]
+ exit_marker.assert_called_once()
+
+
[email protected]_db(transaction=True)
+async def test_stream_emits_heartbeat_when_idle(team):
+ pubsub_mock = MagicMock()
+ pubsub_mock.get_message = _async_get_message([None, None, _StopStream()])
+
+ patcher, exit_marker = _patch_subscribe(pubsub_mock)
+ # Force heartbeat threshold to zero so any idle tick emits one.
+ with (
+ patcher,
+ patch("products.wizard.backend.presentation.sessions.config.SSE_HEARTBEAT_INTERVAL_SECONDS", 0.0),
+ ):
+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
+ events = await _drain(gen, max_events=4)
+
+ assert events == [b": ping\n\n", b": ping\n\n"]
+ exit_marker.assert_called_once()
+
+
[email protected]_db(transaction=True)
+async def test_stream_terminates_on_max_duration(team):
+ """SSE_MAX_DURATION_SECONDS=0 -> first loop tick emits `event: end` and exits."""
+ pubsub_mock = MagicMock()
+ pubsub_mock.get_message = _async_get_message([None] * 10)
+
+ patcher, exit_marker = _patch_subscribe(pubsub_mock)
+ with (
+ patcher,
+ patch("products.wizard.backend.presentation.sessions.config.SSE_MAX_DURATION_SECONDS", 0),
+ ):
+ gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
+ events = await _drain(gen, max_events=5)
+
+ # Generator emits `event: end` then returns — clean close, no leaked
+ # subscription.
+ assert events == [b"event: end\ndata: reconnect\n\n"]
+ exit_marker.assert_called_once()
diff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.py
index e77f2e34d258..6b0d536cd0b1 100644
--- a/products/wizard/backend/tests/test_presentation.py
+++ b/products/wizard/backend/tests/test_presentation.py
@@ -95,7 +95,7 @@ class TestWizardSessionViewSet(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- @patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")
+ @patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
def test_completed_session_accepts_event_definition_write_scope(self, _mock_sync):
self._authenticate_personal_api_key(["wizard_session:write", "event_definition:write"])
@@ -107,7 +107,7 @@ class TestWizardSessionViewSet(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- @patch("products.wizard.backend.logic.sessions.sync_wizard_event_definitions.delay")
+ @patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
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)