:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): let users cancel cloud runs and stop counting failed runs against quota (#73001)
Fernando Gomesf47d6158a7fe
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 27209886b358..b84a72ced133 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -106,9 +106,11 @@ PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {"wizard_runs": "wizard_run",}-# Per-user wizard-run budget, mirroring the session endpoint's DRF throttles-# (SetupWizardCloudRunBurstRateThrottle 2/hour, SetupWizardCloudRunSustainedRateThrottle-# 5/day) which can't run here — the partner path has no session user on the request.+# Per-user wizard-run budget matching the session endpoint's limits (2/hour, 5/day), which+# can't run here — the partner path has no session user on the request. Unlike the session+# endpoint's throttles, which count only non-failed/non-cancelled runs from the DB, this is a+# plain request counter: failed runs still consume partner quota. Aligning it with the+# outcome-aware counting is a pending follow-up.WIZARD_RUN_USER_RATE_LIMIT_PREFIX = "provisioning_wizard_run_user:"WIZARD_RUN_USER_RATE_LIMITS: list[tuple[str, int, int]] = [("burst", 2, 3600),diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsxindex e16f45c9234c..127eaaf7ba91 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx@@ -90,6 +90,8 @@ function WizardSyncDialog({isOpen,onClose,onClear,+ onCancel,+ cancelling = false,onDashboardClick,}: {progress: InstallationProgress@@ -99,6 +101,8 @@ function WizardSyncDialog({isOpen: booleanonClose: () => voidonClear?: () => void+ onCancel?: () => void+ cancelling?: booleanonDashboardClick?: () => void}): JSX.Element {const isTerminal = progress.phase === 'completed' || progress.phase === 'error'@@ -122,6 +126,19 @@ function WizardSyncDialog({Dismiss this run</LemonButton>)}+ {!isTerminal && onCancel && (+ <LemonButton+ type="secondary"+ status="danger"+ onClick={onCancel}+ loading={cancelling}+ disabledReason={cancelling ? 'Cancelling the run' : undefined}+ className="self-end"+ data-attr="wizard-sync-cancel-run"+ >+ Cancel run+ </LemonButton>+ )}</div></LemonModal>)@@ -136,6 +153,8 @@ function WizardSyncSurface({mode,runKey,onClear,+ onCancel,+ cancelling = false,hideCard = false,}: {progress: InstallationProgress@@ -146,6 +165,9 @@ function WizardSyncSurface({mode: WizardSyncModerunKey: stringonClear?: () => void+ /** Cancels the run server-side (cloud runs only) — shown in the dialog while the run is live. */+ onCancel?: () => void+ cancelling?: booleanhideCard?: boolean}): JSX.Element {const { dismissedKey, dialogOpen } = useValues(wizardSyncUiLogic)@@ -246,6 +268,8 @@ function WizardSyncSurface({isOpen={dialogOpen}onClose={closeDialog}onClear={handleClear}+ onCancel={onCancel}+ cancelling={cancelling}/></>)@@ -256,7 +280,8 @@ function WizardSyncCloudFab({ handle, hideCard }: { handle: CloudRunHandle; hideconst { installationProgress, taskRunState } = useValues(installationProgressLogic({ mode: 'cloud', runId: handle.runId, taskId: handle.taskId }))- const { clearActiveCloudRun } = useActions(activeCloudRunLogic)+ const { cancellingRun } = useValues(activeCloudRunLogic)+ const { clearActiveCloudRun, cancelActiveCloudRun } = useActions(activeCloudRunLogic)const isTerminal = installationProgress.phase === 'completed' || installationProgress.phase === 'error'return (<WizardSyncSurface@@ -266,6 +291,8 @@ function WizardSyncCloudFab({ handle, hideCard }: { handle: CloudRunHandle; hidemode="cloud"runKey={handle.runId}onClear={clearActiveCloudRun}+ onCancel={cancelActiveCloudRun}+ cancelling={cancellingRun}hideCard={hideCard}/>)diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.tsindex 6fa7cfbac98e..23e6016b9e26 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts@@ -7,15 +7,17 @@ import { userLogic } from 'scenes/userLogic'import { initKeaTests } from '~/test/init'-import { tasksActiveWizardRunRetrieve } from 'products/tasks/frontend/generated/api'+import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'import { activeCloudRunLogic, CloudRunHandle, scopedCloudRun } from './activeCloudRunLogic'jest.mock('products/tasks/frontend/generated/api', () => ({tasksActiveWizardRunRetrieve: jest.fn(),+ tasksRunsCancelCreate: jest.fn(),}))const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mock+const mockRunCancel = tasksRunsCancelCreate as jest.Mockconst handle: CloudRunHandle = {taskId: 'task-1',@@ -130,6 +132,82 @@ describe('activeCloudRunLogic', () => {expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'local-task' })})+ it('cancels the active run and recovers the button once the request settles', async () => {+ setUser(true)+ // Server-side hydration confirms the same run, so it must not clear the local handle mid-test.+ mockActiveWizardRun.mockResolvedValue({+ task_id: 'task-1',+ run_id: 'run-1',+ status: 'in_progress',+ started_at: '2026-01-01T00:00:00Z',+ })+ mockRunCancel.mockResolvedValue({ id: 'run-1', status: 'cancelled' })+ logic = activeCloudRunLogic()+ logic.mount()+ logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)++ logic.actions.cancelActiveCloudRun()+ expect(logic.values.cancellingRun).toBe(true)+ await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunSuccess'])++ expect(mockRunCancel).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 'task-1', 'run-1')+ // The handle stays: the run stream delivers the terminal status, and the user dismisses+ // the finished run as usual. Cancelling resets so a dead stream can't strand a+ // permanently disabled button (a repeat cancel is idempotent server-side).+ expect(logic.values.activeCloudRun).not.toBeNull()+ expect(logic.values.cancellingRun).toBe(false)+ })++ it('recovers the cancel button when the cancel request fails', async () => {+ setUser(true)+ mockActiveWizardRun.mockResolvedValue({+ task_id: 'task-1',+ run_id: 'run-1',+ status: 'in_progress',+ started_at: '2026-01-01T00:00:00Z',+ })+ mockRunCancel.mockRejectedValue(new Error('temporal unavailable'))+ logic = activeCloudRunLogic()+ logic.mount()+ logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)++ logic.actions.cancelActiveCloudRun()+ await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunFailure'])++ // A failed cancel must not strand the button in a loading state or drop the run.+ expect(logic.values.cancellingRun).toBe(false)+ expect(logic.values.activeCloudRun).not.toBeNull()+ })++ it('resets an in-flight cancelling state when a new run handle is set', () => {+ // The flag belongs to the run it was set for; a new run (startCloudRun or server+ // hydration) must start with a usable Cancel button, not one disabled by the old run.+ setUser(true)+ mockActiveWizardRun.mockResolvedValue(undefined)+ mockRunCancel.mockReturnValue(new Promise(() => {}))+ logic = activeCloudRunLogic()+ logic.mount()+ logic.actions.setActiveCloudRun('task-1', 'run-1', '2026-01-01T00:00:00Z', MOCK_TEAM_ID)+ logic.actions.cancelActiveCloudRun()+ expect(logic.values.cancellingRun).toBe(true)++ logic.actions.setActiveCloudRun('task-2', 'run-2', '2026-01-02T00:00:00Z', MOCK_TEAM_ID)++ expect(logic.values.cancellingRun).toBe(false)+ })++ it('does not call the cancel endpoint without an active handle', async () => {+ setUser(true)+ mockActiveWizardRun.mockResolvedValue(undefined)+ logic = activeCloudRunLogic()+ logic.mount()++ logic.actions.cancelActiveCloudRun()+ await expectLogic(logic).toDispatchActions(['cancelActiveCloudRun', 'cancelActiveCloudRunFailure'])++ expect(mockRunCancel).not.toHaveBeenCalled()+ })+it('clears a stale local handle when the server reports no active run', async () => {// A returning provisioned user whose run finished/was abandoned still has a handle in// localStorage. Hydration must reconcile it away, or the install card and FAB keepdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.tsindex b18c0be38960..929f0a20f057 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts@@ -1,10 +1,12 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { subscriptions } from 'kea-subscriptions'+import { lemonToast } from '@posthog/lemon-ui'+import { projectLogic } from 'scenes/projectLogic'import { userLogic } from 'scenes/userLogic'-import { tasksActiveWizardRunRetrieve } from 'products/tasks/frontend/generated/api'+import { tasksActiveWizardRunRetrieve, tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'export interface CloudRunHandle {taskId: string@@ -29,12 +31,22 @@ export interface activeCloudRunLogicValues {isProvisionedUser: boolean // userLogicactiveCloudRun: CloudRunHandle | nullcanHydrateFromServer: boolean+ cancellingRun: booleanpanelMounted: booleanpersistedCloudRun: CloudRunHandle | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface activeCloudRunLogicActions {+ cancelActiveCloudRun: () => {+ value: true+ }+ cancelActiveCloudRunFailure: () => {+ value: true+ }+ cancelActiveCloudRunSuccess: () => {+ value: true+ }clearActiveCloudRun: () => {value: true}@@ -106,6 +118,12 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([// Ask the server whether the current project has an active wizard cloud run, seeding the// handle when the drop flow started the run server-side (so no local handle was ever written).hydrateFromServer: true,+ // Ask the backend to cancel the active run (terminates the workflow and tears down the+ // sandbox). The handle is kept: the run stream delivers the terminal `cancelled` status,+ // so the surface shows the outcome and the user dismisses it like any finished run.+ cancelActiveCloudRun: true,+ cancelActiveCloudRunSuccess: true,+ cancelActiveCloudRunFailure: true,}),reducers({persistedCloudRun: [@@ -127,6 +145,21 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([setPanelMounted: (_, { mounted }) => mounted,},],+ // Guards the Cancel button against double-submission while the request is in flight.+ // It resets on success too: the terminal status normally arrives via the stream and+ // removes the button, but if the stream disconnects first, a permanently disabled+ // button would strand the user — a repeat cancel is idempotent server-side. A new+ // handle also resets it, since the flag belongs to the run it was set for.+ cancellingRun: [+ false,+ {+ cancelActiveCloudRun: () => true,+ cancelActiveCloudRunSuccess: () => false,+ cancelActiveCloudRunFailure: () => false,+ clearActiveCloudRun: () => false,+ setActiveCloudRun: () => false,+ },+ ],}),selectors({activeCloudRun: [@@ -144,6 +177,21 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([],}),listeners(({ actions, values }) => ({+ cancelActiveCloudRun: async () => {+ const handle = values.activeCloudRun+ const projectId = values.currentProjectId+ if (!handle || projectId == null) {+ actions.cancelActiveCloudRunFailure()+ return+ }+ try {+ await tasksRunsCancelCreate(String(projectId), handle.taskId, handle.runId)+ actions.cancelActiveCloudRunSuccess()+ } catch {+ lemonToast.error('Could not cancel the run. Please try again.')+ actions.cancelActiveCloudRunFailure()+ }+ },hydrateFromServer: async () => {// The drop flow starts the run server-side, so a freshly-signed-in provisioned user has// no localStorage handle. Only they need the extra request; everyone else already has adiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.tsindex 7871555408eb..5b8df8f4091c 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts@@ -74,6 +74,16 @@ describe('installationProgressLogic merge', () => {expect(cloudProgress(state, [], conn, null).phase).toBe(expected)})+ it.each([+ // A deliberate cancel (button or PR close) must not read as a broken installation.+ ['cancelled', 'Run cancelled'],+ ['failed', 'Installation failed'],+ ])('titles a terminal %s run as %s', (status, expectedTitle) => {+ const result = cloudProgress(taskState({ status, error_message: 'Stopped by user' }), [], 'open', null)+ expect(result.error?.title).toBe(expectedTitle)+ expect(result.error?.detail).toBe('Stopped by user')+ })+it('surfaces a stalled queued run as an error instead of an eternal spinner', () => {const result = cloudProgress(taskState({ status: 'queued' }), [], 'open', null, true)expect(result.phase).toBe('error')diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.tsindex 4b5a61e437ba..f8b79f3020c0 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts@@ -267,7 +267,9 @@ export function cloudProgress(const error =phase === 'error'? (stalledError ?? {- title: 'Installation failed',+ // A cancelled run is a deliberate stop (Cancel button or closing the setup PR),+ // not a broken installation — presenting it as a failure reads as a bug.+ title: taskRunState?.status === 'cancelled' ? 'Run cancelled' : 'Installation failed',detail:taskRunState?.error_message ?? (session?.error as { message?: string } | null)?.message ?? null,})diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex df3a4e9cf05d..edfc266cb5cc 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -1,8 +1,9 @@from __future__ import annotationsimport json+import timeimport hashlib-from typing import cast+from typing import NoReturn, castfrom django.conf import settingsfrom django.core.cache import cache@@ -54,9 +55,15 @@ ERROR_PROJECT_NOT_FOUND = "This project does not exist."OPENAI_SUPPORTED_MODELS = {"o4-mini", "gpt-5-mini", "gpt-5-nano", "gpt-5"}+# Absolute ceiling on sandbox boots per user per day, reserved atomically right before run+# creation. The DB-counted throttles above the view are read-then-create and can be raced by+# parallel requests; this cache.incr cannot, so it is the hard bound a start-cancel or crash+# loop lands on. Only requests that reach creation consume it.+WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP = 15+WIZARD_CLOUD_RUN_REQUESTS_TOTAL = Counter("posthog_wizard_cloud_run_requests_total",- "Cloud-run wizard kickoff requests, by outcome (created/unavailable/invalid/permission_denied)",+ "Cloud-run wizard kickoff requests, by outcome (created/unavailable/invalid/permission_denied/throttled)",labelnames=["outcome"],)@@ -151,6 +158,13 @@ class SetupWizardViewSet(viewsets.ViewSet):return []+ def throttled(self, request: Request, wait: float) -> NoReturn:+ # 429s never reach the action body, so without this the kickoff counter is blind to+ # rate-limited users and throttle pressure is invisible in dashboards.+ if self.action == "cloud_run":+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="throttled").inc()+ super().throttled(request, wait)+@action(methods=["POST"], detail=False, url_path="initialize")def initialize(self, request: Request) -> Response:"""@@ -430,7 +444,10 @@ class SetupWizardViewSet(viewsets.ViewSet):url_path="cloud_run",authentication_classes=[SessionAuthentication],permission_classes=[IsAuthenticated],- throttle_classes=[SetupWizardCloudRunBurstRateThrottle, SetupWizardCloudRunSustainedRateThrottle],+ throttle_classes=[+ SetupWizardCloudRunBurstRateThrottle,+ SetupWizardCloudRunSustainedRateThrottle,+ ],)def cloud_run(self, request: Request) -> Response:"""Run the PostHog setup wizard in the cloud against the user's GitHub repository.@@ -452,9 +469,33 @@ class SetupWizardViewSet(viewsets.ViewSet):except exceptions.ValidationError:WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="invalid").inc()raise+ except exceptions.Throttled:+ # The atomic attempt reservation inside _cloud_run raises after check_throttles+ # ran, so the throttled() hook below never sees it.+ WIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="throttled").inc()+ raiseWIZARD_CLOUD_RUN_REQUESTS_TOTAL.labels(outcome="created").inc()return response+ @staticmethod+ def _reserve_cloud_run_attempt(user_id: int) -> None:+ """Atomically consume one of the user's daily cloud-run attempts or raise Throttled.++ Runs after validation and project access checks, immediately before run creation, so+ rejected requests never consume the budget — while parallel requests cannot all slip+ under the ceiling the way they can with the read-then-create DB throttles.+ """+ window = int(time.time()) // 86400+ key = f"wizard_cloud_run_attempts:{user_id}:{window}"+ cache.add(key, 0, timeout=86400)+ try:+ count = cache.incr(key)+ except ValueError:+ # The key expired between add and incr; this request is the window's first.+ count = 1+ if count > WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP:+ raise exceptions.Throttled(detail="You've reached today's limit for cloud setup runs. Try again tomorrow.")+def _cloud_run(self, request: Request) -> Response:if not bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID):raise exceptions.NotFound("Running the setup wizard in the cloud is not available.")@@ -474,6 +515,8 @@ class SetupWizardViewSet(viewsets.ViewSet):if project.id not in visible_project_ids:raise exceptions.PermissionDenied("You don't have access to this project.")+ self._reserve_cloud_run_attempt(cast(User, request.user).id)+try:result = tasks_facade.create_wizard_cloud_run(team=project.passthrough_team,diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 0eddec4c93cd..ce3b031e91e0 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -1,4 +1,5 @@import json+from datetime import timedeltafrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -6,6 +7,7 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cachefrom django.test import override_settingsfrom django.urls import reverse+from django.utils import timezonefrom rest_framework import status@@ -528,6 +530,48 @@ class SetupWizardCloudRunTests(APIBaseTest):)assert response.status_code == status.HTTP_403_FORBIDDEN+ @patch("products.tasks.backend.facade.api.recent_wizard_cloud_run_times")+ @patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")+ def test_throttles_when_quota_counting_runs_reports_the_cap(self, mock_create, mock_run_times):+ # Wiring guard for the outcome-aware throttles: the endpoint must consult the facade's+ # run count (the exclusion behavior itself is covered in the tasks product's facade tests).+ mock_run_times.return_value = [timezone.now() - timedelta(minutes=5), timezone.now() - timedelta(minutes=1)]++ response = self.client.post(+ self.CLOUD_RUN_URL,+ data={"project_id": self.team.id, "repository": "acme/app"},+ format="json",+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ mock_create.assert_not_called()++ @patch("posthog.api.wizard.http.WIZARD_CLOUD_RUN_DAILY_ATTEMPT_CAP", 2)+ @patch("products.tasks.backend.facade.api.recent_wizard_cloud_run_times")+ @patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")+ def test_attempt_reservation_is_a_hard_ceiling_regardless_of_run_outcome(self, mock_create, mock_run_times):+ # The DB-counted throttles ignore failed/cancelled runs, so the atomic reservation is+ # the only thing bounding a start-fail or start-cancel loop.+ mock_run_times.return_value = []+ mock_create.return_value = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))++ for _ in range(2):+ response = self.client.post(+ self.CLOUD_RUN_URL,+ data={"project_id": self.team.id, "repository": "acme/app"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.content++ response = self.client.post(+ self.CLOUD_RUN_URL,+ data={"project_id": self.team.id, "repository": "acme/app"},+ format="json",+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert mock_create.call_count == 2+def tearDown(self):super().tearDown()cache.clear() # Clears out all DRF throttle datadiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 3dd82fbfbbce..eb18281022e8 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -3,15 +3,24 @@ import jsonimport timeimport hashlibfrom contextlib import suppress+from datetime import timedeltafrom functools import lru_cache+from typing import TYPE_CHECKINGfrom django.conf import settingsfrom django.urls import resolve+from django.utils import timezonefrom prometheus_client import Counterfrom rest_framework.throttling import SimpleRateThrottle, UserRateThrottlefrom statshog.defaults.django import statsd+if TYPE_CHECKING:+ # This module is imported by DRF's DEFAULT_THROTTLE_CLASSES setting while rest_framework.views+ # is still initializing, so importing it (or anything that pulls it in) at runtime is circular.+ from rest_framework.request import Request+ from rest_framework.views import APIView+from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthenticationfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exception@@ -870,14 +879,61 @@ class SetupWizardQueryRateThrottle(SimpleRateThrottle):return f"throttle_wizard_query_{sha_hash}"-class SetupWizardCloudRunBurstRateThrottle(UserRateThrottle):- # "Run the setup wizard in the cloud" provisions a Modal sandbox and runs an LLM agent per call,- # so cap it hard per user — a couple per hour only, with an absolute daily ceiling (sustained throttle below).+class SetupWizardCloudRunOutcomeAwareThrottle(UserRateThrottle):+ """Counts a user's recent wizard cloud RUNS (not requests), excluding failed and cancelled ones.++ Each cloud run provisions a Modal sandbox and runs an LLM agent, so the cap must stay hard — but+ counting raw requests locks users out after a run fails or gets cancelled, exactly when they need+ to retry. Run outcomes change after the request, so this counts run rows in the DB at request+ time instead of DRF's cache-side request history. Requests that boot no sandbox (validation+ errors, missing GitHub integration, 429s from a sibling throttle) consume no quota — DRF+ evaluates every throttle on every request, so a cache-side counter would silently charge+ rejected requests.++ These DB counts are read-then-create and can be raced by parallel requests, so they are the+ user-facing soft limits; the hard ceiling on sandbox boots is the atomic per-request attempt+ reservation inside the cloud_run view itself.+ """++ # Assigned by SimpleRateThrottle.__init__ from the parsed rate; the stubs don't declare them.+ num_requests: int+ duration: int++ def allow_request(self, request: "Request", view: "APIView") -> bool:+ user = getattr(request, "user", None)+ if user is None or not user.is_authenticated:+ # cloud_run requires IsAuthenticated; anything else is rejected by permissions.+ return True+ # DRF evaluates both sibling throttles on every request; memoizing on the request keeps+ # that at one DB read per distinct window instead of one per throttle.+ memo = getattr(request, "_wizard_run_times_memo", None)+ if memo is None:+ memo = {}+ setattr(request, "_wizard_run_times_memo", memo) # noqa: B010 — dynamic attr the stubs don't know+ if self.duration not in memo:+ # Deferred: rate_limit is core and imports at module scope would pull the tasks+ # product into every process's import path.+ from products.tasks.backend.facade.api import recent_wizard_cloud_run_times # noqa: PLC0415++ memo[self.duration] = recent_wizard_cloud_run_times(+ user.pk, timezone.now() - timedelta(seconds=self.duration)+ )+ self._recent_run_times = memo[self.duration]+ return len(self._recent_run_times) < self.num_requests++ def wait(self) -> float | None:+ run_times = getattr(self, "_recent_run_times", None)+ if not run_times:+ return None+ return max((run_times[0] + timedelta(seconds=self.duration) - timezone.now()).total_seconds(), 0)+++class SetupWizardCloudRunBurstRateThrottle(SetupWizardCloudRunOutcomeAwareThrottle):scope = "wizard_cloud_run_burst"rate = "2/hour"-class SetupWizardCloudRunSustainedRateThrottle(UserRateThrottle):+class SetupWizardCloudRunSustainedRateThrottle(SetupWizardCloudRunOutcomeAwareThrottle):scope = "wizard_cloud_run_day"rate = "5/day"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a427210a1cb2..fc2e8aed4c80 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -901,6 +901,35 @@ def create_wizard_cloud_run()+def recent_wizard_cloud_run_times(user_id: int, since: datetime) -> list[datetime]:+ """Creation times of a user's recent wizard cloud runs that still count against their quota.++ Backs the outcome-aware cloud_run throttles: failed and cancelled runs are excluded so a+ user whose run broke (or who cancelled a stuck one) can start another without waiting out+ the window. The hard ceiling on total attempts lives in the cloud_run view as an atomic+ cache reservation, not here.++ The filter trusts only PATCH-immutable markers: ``created_by`` (set at creation) and the+ protected ``wizard_config`` state key that only ``create_wizard_cloud_run`` stamps (see+ ``_PROTECTED_RUN_STATE_KEYS``). Mutable fields like the run's ``environment`` are+ deliberately NOT filtered — a run PATCHed from cloud to local must keep consuming quota,+ or flipping it would launder sandbox boots out of the limits.++ Deliberately user-scoped across teams: the throttle is per user, and a user can run the+ wizard on projects in different teams. Returns only timestamps, no run data.+ """+ return list(+ TaskRun.objects.filter(+ task__created_by_id=user_id,+ state__has_key="wizard_config",+ created_at__gte=since,+ )+ .exclude(status__in=[TaskRun.Status.FAILED, TaskRun.Status.CANCELLED])+ .order_by("created_at")+ .values_list("created_at", flat=True)+ )++def create_task_without_run(*,team,diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 2c23c637418a..53af1386f636 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -585,3 +585,80 @@ class TestFacadeReadsAndMappers(TestCase):# overlap-clone-boot launch (before run_wizard) burns the prompt on an untouched repo# and the run never opens a PR. Wizard runs must pin the overlap boot off.self.assertIs(run.state.get("overlap_clone_boot_enabled"), False)+++class TestRecentWizardCloudRunTimes(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ other_team: ClassVar[Team]+ user: ClassVar[User]+ other_user: ClassVar[User]++ @classmethod+ def setUpTestData(cls):+ cls.organization = Organization.objects.create(name="Quota Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Quota Team")+ cls.other_team = Team.objects.create(organization=cls.organization, name="Other Quota Team")+ cls.user = User.objects.create(email="[email protected]", distinct_id="quota-distinct")+ cls.other_user = User.objects.create(email="[email protected]", distinct_id="quota-other-distinct")++ def _make_run(+ self,+ *,+ status=TaskRun.Status.IN_PROGRESS,+ origin_product=Task.OriginProduct.ONBOARDING,+ environment=TaskRun.Environment.CLOUD,+ state=None,+ team=None,+ created_by=None,+ ) -> TaskRun:+ task = Task.objects.create(+ team=team or self.team,+ title="Set up PostHog",+ description="wizard",+ origin_product=origin_product,+ created_by=created_by or self.user,+ repository="acme/app",+ )+ return TaskRun.objects.create(+ task=task,+ team=team or self.team,+ status=status,+ environment=environment,+ state={"wizard_config": {}} if state is None else state,+ )++ @parameterized.expand(+ [+ # Failed and cancelled runs must not consume quota: users retry exactly when a run broke.+ ("failed_run", {"status": TaskRun.Status.FAILED}, 0),+ ("cancelled_run", {"status": TaskRun.Status.CANCELLED}, 0),+ ("in_progress_run", {"status": TaskRun.Status.IN_PROGRESS}, 1),+ ("queued_run", {"status": TaskRun.Status.QUEUED}, 1),+ ("completed_run", {"status": TaskRun.Status.COMPLETED}, 1),+ # Only the PATCH-immutable wizard_config marker decides membership. Mutable fields+ # (environment, origin_product) must NOT be filtered, or a user could PATCH a run+ # to local and launder sandbox boots out of the quota.+ ("run_patched_to_local", {"environment": TaskRun.Environment.LOCAL}, 1),+ ("non_onboarding_task_with_marker", {"origin_product": Task.OriginProduct.USER_CREATED}, 1),+ ("run_without_wizard_config", {"state": {}}, 0),+ ]+ )+ def test_counts_only_quota_consuming_runs(self, _name, run_kwargs, expected_count):+ self._make_run(**run_kwargs)+ since = django_timezone.now() - timedelta(hours=1)+ self.assertEqual(len(facade.recent_wizard_cloud_run_times(self.user.id, since)), expected_count)++ def test_scopes_by_user_across_teams_and_respects_window(self):+ self._make_run()+ # Same user, different team: the throttle is per user, so this counts too.+ self._make_run(team=self.other_team)+ # Another user's run must never consume this user's quota.+ self._make_run(created_by=self.other_user)+ old_run = self._make_run()+ TaskRun.objects.filter(id=old_run.id).update(created_at=django_timezone.now() - timedelta(hours=3))++ since = django_timezone.now() - timedelta(hours=1)+ times = facade.recent_wizard_cloud_run_times(self.user.id, since)+ self.assertEqual(len(times), 2)+ self.assertEqual(times, sorted(times))diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 327ef4d8b542..90e5e3a1743b 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -303,6 +303,77 @@ class TestGitHubPRWebhook(TestCase):assert run.output is not Noneself.assertIs(run.output.get("pr_merged"), True)+ def _closed_pr_payload(self, pr_url: str) -> dict:+ return {+ "action": "closed",+ "pull_request": {+ "html_url": pr_url,+ "merged": False,+ },+ }++ @parameterized.expand(+ [+ ("wizard_run_in_progress", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.CLOUD, 1),+ ("wizard_run_queued", {"wizard_config": {}}, TaskRun.Status.QUEUED, TaskRun.Environment.CLOUD, 1),+ ("non_wizard_run", {}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.CLOUD, 0),+ ("already_terminal_run", {"wizard_config": {}}, TaskRun.Status.COMPLETED, TaskRun.Environment.CLOUD, 0),+ ("local_run", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.LOCAL, 0),+ ]+ )+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_closed_cancels_wizard_run(+ self, _name, state, status, environment, expected_cancels, _mock_capture, mock_get_secret+ ):+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/780"+ run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=status,+ environment=environment,+ state=state,+ output={"pr_url": pr_url},+ )++ with patch("products.tasks.backend.webhooks.cancel_task_run") as mock_cancel:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._make_webhook_request(self._closed_pr_payload(pr_url))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(mock_cancel.call_count, expected_cancels)+ if expected_cancels:+ mock_cancel.assert_called_once_with(+ run.id,+ run.task_id,+ run.team_id,+ reason="Setup pull request was closed",+ source="pr_closed",+ )++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_closed_cancel_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/781"+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"wizard_config": {}},+ output={"pr_url": pr_url},+ )++ with patch(+ "products.tasks.backend.webhooks.cancel_task_run",+ side_effect=RuntimeError("temporal unreachable"),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ response = self._make_webhook_request(self._closed_pr_payload(pr_url))++ self.assertEqual(response.status_code, 200)+@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@patch("products.tasks.backend.models.posthoganalytics.capture")def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex e65c7edc3a23..b4d69b90a496 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -16,6 +16,7 @@ from posthog.models.team.team import Teamfrom products.signals.backend.models import InvalidStatusTransition, SignalReportfrom products.tasks.backend.facade.api import signal_workflow_completion+from products.tasks.backend.facade.cancellation import cancel_task_runfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX@@ -197,6 +198,12 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:_record_run_pr_merged(task_run)_resolve_signal_reports_for_task(task_run.task_id, pr_url)+ if task_run and action == "closed" and not merged:+ # Same trust rule as the merge branch: only the run that claims this PR URL.+ run_output = task_run.output if isinstance(task_run.output, dict) else {}+ if run_output.get("pr_url") == pr_url:+ _cancel_wizard_run_on_close(task_run)+return HttpResponse(status=200)@@ -273,6 +280,40 @@ def _complete_wizard_run_on_merge(task_run: TaskRun) -> None:transaction.on_commit(_signal)+def _cancel_wizard_run_on_close(task_run: TaskRun) -> None:+ """Cancel a wizard cloud run when its setup PR is closed without merging.++ Closing the setup PR is the user's clearest "I don't want this" signal, yet without this+ hook the workflow keeps the sandbox running until its TTL expires and the onboarding UI+ reports the run as in flight for hours. Scoped to wizard runs: closing a regular task+ run's PR is a normal review action owned by the CI follow-up loop. Best-effort: the+ webhook must stay 2xx even if Temporal is unreachable or the run just finished.+ """+ state = task_run.state if isinstance(task_run.state, dict) else {}+ if "wizard_config" not in state:+ return+ if task_run.environment != TaskRun.Environment.CLOUD:+ return+ if task_run.status in _TERMINAL_RUN_STATUSES:+ return++ def _cancel() -> None:+ try:+ cancel_task_run(+ task_run.id,+ task_run.task_id,+ task_run.team_id,+ reason="Setup pull request was closed",+ source="pr_closed",+ )+ except Exception:+ logger.warning("github_pr_webhook_wizard_cancel_failed", run_id=str(task_run.id), exc_info=True)++ # cancel_task_run does a synchronous Temporal round-trip; on_commit keeps it out of any+ # open transaction and after the webhook's own writes have committed.+ transaction.on_commit(_cancel)++def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, failure_log_event: str) -> bool:"""Idempotently merge ``{key: value}`` into a run's ``output`` JSON under a row lock.