:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(wizard): serialize cloud run admission per user (#97062)
Fernando Gomes5a2f9e117de0
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.mdindex 87071c9eb529..78ae3653ca39 100644--- a/docs/internal/wizard-runs.md+++ b/docs/internal/wizard-runs.md@@ -3,6 +3,14 @@The Wizard is a setup agent distributed as an npm package.A Wizard run records one execution of that agent inside a user-provided workspace.+## Concurrent creation++Cloud run creation holds a PostgreSQL transaction advisory lock for the project and user.+The lock covers the active-run check, rolling hourly and daily limits, and run insertion.+Concurrent requests for the same project and user wait until the first transaction commits or rolls back.+The lock does not lock the `Team` row or serialize different users or projects.+Local runs do not take this lock. Cloud dispatch starts after commit.+## Environments and workspacesV0 supports two configurations:diff --git a/products/wizard/backend/logic/runs/admission.py b/products/wizard/backend/logic/runs/admission.pyindex 2810b86bec57..d0fa8ccfd825 100644--- a/products/wizard/backend/logic/runs/admission.py+++ b/products/wizard/backend/logic/runs/admission.py@@ -1,3 +1,4 @@+from django.db import connectionfrom django.utils import timezonefrom products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus@@ -15,6 +16,14 @@ from products.wizard.backend.logic.runs.config import (from products.wizard.backend.models import WizardRun+def lock_cloud_run_creation(team_id: int, created_by_id: int) -> None:+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",+ [f"wizard-run-admission:{team_id}:{created_by_id}"],+ )++def enforce_cloud_run_creation_policy(team_id: int, created_by_id: int, idempotency_key: str | None = None) -> None:runs = WizardRun.objects.for_team(team_id).filter(created_by_id=created_by_id,diff --git a/products/wizard/backend/logic/runs/lifecycle.py b/products/wizard/backend/logic/runs/lifecycle.pyindex 9678ac96d089..467ded0c7b1a 100644--- a/products/wizard/backend/logic/runs/lifecycle.py+++ b/products/wizard/backend/logic/runs/lifecycle.py@@ -35,7 +35,7 @@ from products.wizard.backend.logic.runs import (cancellation as cancellation_service,store,)-from products.wizard.backend.logic.runs.admission import enforce_cloud_run_creation_policy+from products.wizard.backend.logic.runs.admission import enforce_cloud_run_creation_policy, lock_cloud_run_creationfrom products.wizard.backend.logic.runs.dispatch import dispatch_created_cloud_wizard_run_to_temporal_workerfrom products.wizard.backend.logic.runs.errors import WizardRunDispatchErrorfrom products.wizard.backend.logic.runs.fingerprints import create_run_request_fingerprint@@ -99,6 +99,7 @@ def create_run_with_result(params: CreateWizardRunInput) -> WizardRunCreationReswith database_transaction.atomic():if is_cloud_run:+ lock_cloud_run_creation(params.team_id, params.created_by_id)enforce_cloud_run_creation_policy(params.team_id, params.created_by_id, params.idempotency_key)result = store.create_run(diff --git a/products/wizard/backend/tests/runs/test_concurrent_creation.py b/products/wizard/backend/tests/runs/test_concurrent_creation.pynew file mode 100644index 000000000000..34b493b74152--- /dev/null+++ b/products/wizard/backend/tests/runs/test_concurrent_creation.py@@ -0,0 +1,117 @@+from concurrent.futures import ThreadPoolExecutor+from dataclasses import replace+from datetime import timedelta++import pytest+from unittest.mock import patch++from django.db import OperationalError, connection, connections, transaction+from django.utils import timezone++from posthog.models import Team, User+from posthog.models.scoping import team_scope++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import (+ CreateWizardRunInput,+ GitRepositoryWorkspace,+ WizardRunCreationResult,+)+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus+from products.wizard.backend.facade.errors import (+ ActiveWizardRunError,+ WizardRunDailyLimitError,+ WizardRunHourlyLimitError,+)+from products.wizard.backend.logic.programs import program_to_mapping+from products.wizard.backend.logic.registry.config import POSTHOG_INTEGRATION_PROGRAM+from products.wizard.backend.logic.runs.admission import lock_cloud_run_creation+from products.wizard.backend.logic.runs.config import CLOUD_RUN_DAILY_LIMIT, CLOUD_RUN_HOURLY_LIMIT+from products.wizard.backend.models import WizardRun+++def _create_on_separate_connection(params: CreateWizardRunInput) -> WizardRunCreationResult:+ try:+ with connection.cursor() as cursor:+ cursor.execute("SET lock_timeout = '1s'")+ with team_scope(params.team_id):+ return wizard_facade.create_run_with_result(params)+ finally:+ connections.close_all()++[email protected]_db(transaction=True)+ "limit,age,policy_error",+ [+ pytest.param(1, timedelta(), ActiveWizardRunError, id="active"),+ pytest.param(CLOUD_RUN_HOURLY_LIMIT, timedelta(minutes=10), WizardRunHourlyLimitError, id="hourly"),+ pytest.param(CLOUD_RUN_DAILY_LIMIT, timedelta(hours=2), WizardRunDailyLimitError, id="daily"),+ ],+)+def test_concurrent_cloud_creation_cannot_bypass_limits(+ team: Team, user: User, limit: int, age: timedelta, policy_error: type[Exception]+) -> None:+ for _ in range(limit - 1):+ run = WizardRun.objects.for_team(team.id).create(+ team_id=team.id,+ created_by_id=user.id,+ environment=WizardRunEnvironment.CLOUD.value,+ workspace_type="git_repository",+ workspace={"repository": "example/project"},+ program=program_to_mapping(POSTHOG_INTEGRATION_PROGRAM),+ status=WizardRunStatus.COMPLETED.value,+ )+ WizardRun.objects.for_team(team.id).filter(id=run.id).update(created_at=timezone.now() - age)++ params = CreateWizardRunInput(+ team_id=team.id,+ created_by_id=user.id,+ environment=WizardRunEnvironment.CLOUD,+ workspace=GitRepositoryWorkspace(repository="example/project"),+ program_id=POSTHOG_INTEGRATION_PROGRAM.id,+ idempotency_key="first-request",+ )+ competing_params = replace(params, idempotency_key="second-request")++ with (+ patch("products.wizard.backend.logic.runs.lifecycle.authorize_git_repository_access"),+ patch("products.wizard.backend.logic.runs.lifecycle._dispatch_cloud_run"),+ ):+ with transaction.atomic():+ first = wizard_facade.create_run_with_result(params)+ with ThreadPoolExecutor(max_workers=1) as executor:+ competing_request = executor.submit(_create_on_separate_connection, competing_params)+ with pytest.raises(OperationalError, match="lock timeout"):+ competing_request.result(timeout=10)++ if policy_error is not ActiveWizardRunError:+ WizardRun.objects.for_team(team.id).filter(id=first.run.id).update(+ status=WizardRunStatus.COMPLETED.value+ )++ with pytest.raises(policy_error):+ wizard_facade.create_run_with_result(competing_params)++ replay = wizard_facade.create_run_with_result(params)+ assert not replay.created+ assert replay.run.id == first.run.id+ assert WizardRun.objects.for_team(team.id).count() == limit++[email protected]_db(transaction=True)[email protected]("other_team,other_user", [(False, True), (True, False)])+def test_admission_lock_does_not_block_other_scopes(team: Team, user: User, other_team: bool, other_user: bool) -> None:+ def acquire_other_scope() -> None:+ try:+ with transaction.atomic(), connection.cursor() as cursor:+ cursor.execute("SET LOCAL lock_timeout = '1s'")+ lock_cloud_run_creation(team.id + int(other_team), user.id + int(other_user))+ Team.objects.select_for_update(nowait=True).get(id=team.id)+ finally:+ connections.close_all()++ with transaction.atomic():+ lock_cloud_run_creation(team.id, user.id)+ with ThreadPoolExecutor(max_workers=1) as executor:+ executor.submit(acquire_other_scope).result(timeout=10)