Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(wizard): lock the session row once in upsert_session (#110506)

posthog[bot]c245c0c20405
diff --git a/products/wizard/backend/logic/sessions/lifecycle.py b/products/wizard/backend/logic/sessions/lifecycle.py
index 4ee1086e2be4..d9c543831a63 100644
--- a/products/wizard/backend/logic/sessions/lifecycle.py
+++ b/products/wizard/backend/logic/sessions/lifecycle.py
@@ -4,8 +4,9 @@ Business logic for Wizard sessions.
import logging
from functools import partial
+from typing import Any
-from django.db import transaction
+from django.db import IntegrityError, transaction
from kombu.exceptions import OperationalError
@@ -24,68 +25,40 @@ 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 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.
+ 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. The row is locked once and saved directly, because
+ `update_or_create` would lock it a second time. If a concurrent push for a
+ brand-new session_id inserts the row first, this push locks that row and
+ updates it.
"""
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
+ session = _lock_session(params)
+ created = False
+ if session is None:
+ try:
+ with transaction.atomic():
+ # created_by is set only here so a later push for the same run can't reattribute it.
+ session = WizardSession.objects.create(
+ team_id=params.team_id,
+ session_id=params.session_id,
+ created_by_id=params.created_by_id,
+ **_session_fields(params, previous_session=None),
+ )
+ created = True
+ except IntegrityError:
+ session = _lock_session(params)
+ if session is None:
+ raise
+
+ previous_run_phase = None if created else session.run_phase
+ if not created:
+ _check_owner(session, params)
+ fields = _session_fields(params, previous_session=session)
+ for name, value in fields.items():
+ setattr(session, name, value)
+ session.save(update_fields=[*fields, "updated_at"])
- # A session belongs to the user who created it. A later push from a
- # different user would overwrite the run data while `created_by` stays
- # the original owner, so reject it. Legacy rows with a null
- # `created_by_id` predate attribution and stay updatable by anyone.
- if (
- previous_session is not None
- and previous_session.created_by_id is not None
- and previous_session.created_by_id != params.created_by_id
- ):
- 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 == 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
- # (an ordering race between debounced snapshots, or an older CLI) must not wipe it.
- # A new run is a new session_id, so nothing ever needs to clear the field.
- handoff_text = params.handoff_text
- if not handoff_text and previous_session:
- handoff_text = previous_session.handoff_text
-
- 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,
- "pending_input": params.pending_input,
- "handoff_text": handoff_text,
- }
- # created_by only in create_defaults so a later push for the same run can't reattribute it.
- instance, created = WizardSession.objects.update_or_create(
- team_id=params.team_id,
- session_id=params.session_id,
- defaults=defaults,
- create_defaults={**defaults, "created_by_id": params.created_by_id},
- )
if (
previous_run_phase != WizardSessionRunPhase.COMPLETED.value
and params.run_phase == WizardSessionRunPhase.COMPLETED
@@ -94,13 +67,66 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,
partial(_enqueue_event_definition_sync, params.team_id, params.session_id),
robust=True,
)
- dto = to_session_dto(instance)
+ # Built after the commit, so that a lazy `created_by` load on the create path doesn't run while the row is locked.
+ dto = to_session_dto(session)
report_session_upserted(previous_run_phase, dto)
publish_session_update(dto)
return dto, created
+def _lock_session(params: UpsertWizardSessionInput) -> WizardSession | None:
+ # `created_by` is nullable, so the join is a LEFT OUTER JOIN. Postgres refuses FOR UPDATE on the
+ # nullable side of that join, so `of=("self",)` limits the lock to the session row.
+ return (
+ WizardSession.objects.select_for_update(of=("self",))
+ .select_related("created_by")
+ .filter(team_id=params.team_id, session_id=params.session_id)
+ .first()
+ )
+
+
+def _check_owner(session: WizardSession, params: UpsertWizardSessionInput) -> None:
+ # A session belongs to the user who created it. A later push from a
+ # different user would overwrite the run data while `created_by` stays
+ # the original owner, so reject it. Legacy rows with a null
+ # `created_by_id` predate attribution and stay updatable by anyone.
+ if session.created_by_id is not None and session.created_by_id != params.created_by_id:
+ raise WizardSessionOwnershipError("This wizard session belongs to a different user and can't be updated.")
+
+
+def _session_fields(params: UpsertWizardSessionInput, previous_session: WizardSession | None) -> dict[str, Any]:
+ event_plan = params.event_plan
+ 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
+ # (an ordering race between debounced snapshots, or an older CLI) must not wipe it.
+ # A new run is a new session_id, so nothing ever needs to clear the field.
+ handoff_text = params.handoff_text
+ if not handoff_text and previous_session:
+ handoff_text = previous_session.handoff_text
+
+ return {
+ "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,
+ "pending_input": params.pending_input,
+ "handoff_text": handoff_text,
+ }
+
+
def _enqueue_event_definition_sync(team_id: int, session_id: str) -> None:
try:
sync_wizard_event_definitions.apply_async(
diff --git a/products/wizard/backend/tests/sessions/test_logic.py b/products/wizard/backend/tests/sessions/test_logic.py
index bca2df2a938d..bc0b72eae628 100644
--- a/products/wizard/backend/tests/sessions/test_logic.py
+++ b/products/wizard/backend/tests/sessions/test_logic.py
@@ -3,8 +3,9 @@ from datetime import UTC, datetime
import pytest
from unittest.mock import patch
-from django.db import DatabaseError
+from django.db import DatabaseError, connection
from django.test import override_settings
+from django.test.utils import CaptureQueriesContext
from kombu.exceptions import OperationalError
@@ -88,15 +89,17 @@ 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
- updated, second_created = wizard_facade.upsert(
- _input(
- team.id,
- run_phase=WizardSessionRunPhase.COMPLETED,
- tasks=(WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.COMPLETED),),
+ with CaptureQueriesContext(connection) as queries:
+ updated, second_created = wizard_facade.upsert(
+ _input(
+ team.id,
+ run_phase=WizardSessionRunPhase.COMPLETED,
+ tasks=(WizardTaskDTO(id="1", title="Install SDK", status=WizardSessionTaskStatus.COMPLETED),),
+ )
)
- )
assert second_created is False
+ assert sum("FOR UPDATE" in query["sql"] for query in queries.captured_queries) == 1
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