: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(desktop): handle cloud compute billing denials (#80978)
Adam Bowkerc11be5116551
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 4a0e4c2109ee..51e5525e6a5f 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -1,6 +1,11 @@import { describe, expect, it, vi } from "vitest";import { ApiRequestError } from "./fetcher";-import { CloudCommandError, PostHogAPIClient } from "./posthog-client";+import {+ CloudCommandError,+ CloudUsageLimitError,+ DESKTOP_BILLING_LIMIT_ERROR_CODE,+ PostHogAPIClient,+} from "./posthog-client";describe("PostHogAPIClient", () => {it.each([@@ -1246,6 +1251,34 @@ describe("PostHogAPIClient", () => {}),).rejects.toThrow("Bad Request");});++ it("maps the Desktop billing denial to a cloud usage limit", async () => {+ const body = {+ type: "rate_limit",+ code: DESKTOP_BILLING_LIMIT_ERROR_CODE,+ detail: "Your organization reached its PostHog Desktop usage limit.",+ };+ const fetch = vi+ .fn()+ .mockRejectedValue(+ new ApiRequestError(429, JSON.stringify(body), body),+ );+ const client = makeClient(fetch);++ await expect(+ client.warmTask({ repository: null, github_integration: null }),+ ).rejects.toBeInstanceOf(CloudUsageLimitError);+ });++ it("does not map unrelated 429 responses to billing", async () => {+ const body = { code: "another_rate_limit" };+ const error = new ApiRequestError(429, JSON.stringify(body), body);+ const client = makeClient(vi.fn().mockRejectedValue(error));++ await expect(+ client.warmTask({ repository: null, github_integration: null }),+ ).rejects.toBe(error);+ });});describe("getSignalReport", () => {diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 9e67349ce3e6..2d112ed22ad2 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -190,6 +190,8 @@ export type UsageLimitType = "burst" | "sustained" | null;// Stable message so callers recognize this after a saga reduces the error to a string.export const CLOUD_USAGE_LIMIT_ERROR_MESSAGE = "Cloud usage limit reached";+export const DESKTOP_BILLING_LIMIT_ERROR_CODE =+ "posthog_code_billing_limit_exceeded";export const SESSION_LOGS_MAX_PAGE_SIZE = 5000;@@ -2519,13 +2521,15 @@ export class PostHogAPIClient {const teamId = await this.getTeamId();const { origin_product: originProduct, ...taskOptions } = options;- const data = await this.api.post(`/api/projects/{project_id}/tasks/`, {- path: { project_id: teamId.toString() },- body: {- ...taskOptions,- origin_product: originProduct ?? "user_created",- } as unknown as Schemas.Task,- });+ const data = await this.withCloudUsageLimitCheck(() =>+ this.api.post(`/api/projects/{project_id}/tasks/`, {+ path: { project_id: teamId.toString() },+ body: {+ ...taskOptions,+ origin_product: originProduct ?? "user_created",+ } as unknown as Schemas.Task,+ }),+ );return normalizeTaskResponse(data, { teamId });}@@ -3074,6 +3078,7 @@ export class PostHogAPIClient {} catch (error) {if (error instanceof CloudCommandError) throw error;if (error instanceof ApiRequestError) {+ this.throwIfCloudUsageLimit(error);const backendError = cloudCommandBackendError(error.body);throw new CloudCommandError(method,@@ -3146,34 +3151,36 @@ export class PostHogAPIClient {const teamId = await this.getTeamId();const urlPath = `/api/projects/${teamId}/tasks/warm/`;const url = new URL(`${this.api.baseUrl}${urlPath}`);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: urlPath,- overrides: {- body: JSON.stringify({- repository: options.repository,- repositories: options.repositories,- github_integration: options.github_integration,- branch: options.branch ?? null,- runtime_adapter: options.runtime_adapter ?? null,- model: options.model ?? null,- reasoning_effort: options.reasoning_effort ?? null,- ...(options.context_window- ? { context_window: options.context_window }- : {}),- ...(options.fast_mode != null- ? { fast_mode: options.fast_mode }- : {}),- ...(options.sandbox_environment_id- ? { sandbox_environment_id: options.sandbox_environment_id }- : {}),- ...(options.custom_image_id- ? { custom_image_id: options.custom_image_id }- : {}),- }),- },- });+ const response = await this.withCloudUsageLimitCheck(() =>+ this.api.fetcher.fetch({+ method: "post",+ url,+ path: urlPath,+ overrides: {+ body: JSON.stringify({+ repository: options.repository,+ repositories: options.repositories,+ github_integration: options.github_integration,+ branch: options.branch ?? null,+ runtime_adapter: options.runtime_adapter ?? null,+ model: options.model ?? null,+ reasoning_effort: options.reasoning_effort ?? null,+ ...(options.context_window+ ? { context_window: options.context_window }+ : {}),+ ...(options.fast_mode != null+ ? { fast_mode: options.fast_mode }+ : {}),+ ...(options.sandbox_environment_id+ ? { sandbox_environment_id: options.sandbox_environment_id }+ : {}),+ ...(options.custom_image_id+ ? { custom_image_id: options.custom_image_id }+ : {}),+ }),+ },+ }),+ );if (!response.ok) {throw new Error(`Failed to warm task: ${response.statusText}`);}@@ -3466,11 +3473,13 @@ export class PostHogAPIClient {const url = new URL(`${this.api.baseUrl}/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/resume_in_cloud/`,);- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/resume_in_cloud/`,- });+ const response = await this.withCloudUsageLimitCheck(() =>+ this.api.fetcher.fetch({+ method: "post",+ url,+ path: `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/resume_in_cloud/`,+ }),+ );if (!response.ok) {throw new Error(`Failed to resume run in cloud: ${response.statusText}`);@@ -5320,29 +5329,32 @@ export class PostHogAPIClient {try {return await fn();} catch (error) {- const parsed = this.parseFetcherError(error);- if (- parsed &&- parsed.status === 429 &&- parsed.body.code === "usage_limit_exceeded"- ) {- const limitType = parsed.body.limit_type;- throw new CloudUsageLimitError({- limitType:- limitType === "burst" || limitType === "sustained"- ? limitType- : null,- resetAt:- typeof parsed.body.reset_at === "string"- ? parsed.body.reset_at- : null,- isPro: parsed.body.is_pro === true,- });- }+ this.throwIfCloudUsageLimit(error);throw error;}}+ private throwIfCloudUsageLimit(error: unknown): void {+ const parsed = this.parseFetcherError(error);+ if (+ parsed &&+ parsed.status === 429 &&+ (parsed.body.code === "usage_limit_exceeded" ||+ parsed.body.code === DESKTOP_BILLING_LIMIT_ERROR_CODE)+ ) {+ const limitType = parsed.body.limit_type;+ throw new CloudUsageLimitError({+ limitType:+ limitType === "burst" || limitType === "sustained" ? limitType : null,+ resetAt:+ typeof parsed.body.reset_at === "string"+ ? parsed.body.reset_at+ : null,+ isPro: parsed.body.is_pro === true,+ });+ }+ }+/*** Check if a feature flag is enabled for the current project.* Returns true if the flag exists and is active, false otherwise.diff --git a/products/desktop/packages/core/src/billing/usageLimitContent.test.ts b/products/desktop/packages/core/src/billing/usageLimitContent.test.tsindex ba884c0d82be..0ff269a6eda7 100644--- a/products/desktop/packages/core/src/billing/usageLimitContent.test.ts+++ b/products/desktop/packages/core/src/billing/usageLimitContent.test.ts@@ -7,19 +7,31 @@ describe("usageLimitContent", () => {cause: "model_gate",resetLabel: null,subscribed: false,+ canManageBilling: true,});expect(content.title).toBe("Unlock premium models");expect(content.description).toContain("This model isn't");expect(content.actionLabel).toBe("Add payment method");});+ it("directs members to an administrator for a restricted model", () => {+ const content = usageLimitContent({+ cause: "model_gate",+ resetLabel: null,+ subscribed: false,+ canManageBilling: false,+ });+ expect(content.description).toContain("organization administrator");+ expect(content.actionLabel).toBeNull();+ });+it.each([// Confirmed-free org: allocation used up, the fix is adding a card.[false, "Free usage used up", "Add payment method"],// Subscribed org: the fix is raising the spend limit.- [true, "Organization usage limit reached", "Manage billing"],+ [true, "Organization usage limit reached", "Open Plan & usage"],// Unknown subscription state must not read as free.- [undefined, "Organization usage limit reached", "Manage billing"],+ [undefined, "Organization usage limit reached", "Open Plan & usage"],] as const)("org_limit with subscribed=%s -> %s / %s",(subscribed, title, actionLabel) => {@@ -27,6 +39,7 @@ describe("usageLimitContent", () => {cause: "org_limit",resetLabel: null,subscribed,+ canManageBilling: true,});expect(content.title).toBe(title);expect(content.actionLabel).toBe(actionLabel);@@ -38,6 +51,7 @@ describe("usageLimitContent", () => {cause: "org_limit",resetLabel: "Resets in 3h",subscribed: false,+ canManageBilling: true,});expect(content.title).toBe("Free usage used up");expect(content.description).toContain("Resets in 3h");@@ -48,10 +62,22 @@ describe("usageLimitContent", () => {cause: null,resetLabel: "Resets in 2h",subscribed: true,+ canManageBilling: true,});expect(content.title).toBe("Usage limit reached");expect(content.description).toContain("Resets in 2h");expect(content.actionLabel).toBeNull();expect(content.dismissLabel).toBe("Got it");});++ it("directs members without billing access to an organization administrator", () => {+ const content = usageLimitContent({+ cause: "org_limit",+ resetLabel: null,+ subscribed: true,+ canManageBilling: false,+ });+ expect(content.description).toContain("organization administrator");+ expect(content.actionLabel).toBeNull();+ });});diff --git a/products/desktop/packages/core/src/billing/usageLimitContent.ts b/products/desktop/packages/core/src/billing/usageLimitContent.tsindex a54307bf5b66..5cd032dfa467 100644--- a/products/desktop/packages/core/src/billing/usageLimitContent.ts+++ b/products/desktop/packages/core/src/billing/usageLimitContent.ts@@ -11,10 +11,20 @@ export function usageLimitContent(args: {cause: GatewayLimitCause | null;resetLabel: string | null;subscribed: boolean | undefined;+ canManageBilling: boolean;}): UsageLimitContent {- const { cause, resetLabel, subscribed } = args;+ const { cause, resetLabel, subscribed, canManageBilling } = args;if (cause === "model_gate") {+ if (!canManageBilling) {+ return {+ title: "This model isn't included",+ description:+ "Contact an organization administrator to add a payment method, or switch to an included model.",+ actionLabel: null,+ dismissLabel: "Got it",+ };+ }return {title: "Unlock premium models",description:@@ -25,6 +35,15 @@ export function usageLimitContent(args: {}if (cause === "org_limit") {+ if (!canManageBilling) {+ return {+ title: "Organization usage limit reached",+ description:+ "Your organization has reached its PostHog Desktop credit limit. Contact an organization administrator to change the limit.",+ actionLabel: null,+ dismissLabel: "Got it",+ };+ }if (subscribed === false) {return {title: "Free usage used up",@@ -38,8 +57,8 @@ export function usageLimitContent(args: {return {title: "Organization usage limit reached",description:- "Your organization has reached its spend limit for this billing period. Raise or remove the limit in your PostHog billing settings to keep going.",- actionLabel: "Manage billing",+ "Your organization has reached its PostHog Desktop credit limit. Change the limit in Plan & usage to keep going.",+ actionLabel: "Open Plan & usage",dismissLabel: "Got it",};}diff --git a/products/desktop/packages/shared/src/errors.test.ts b/products/desktop/packages/shared/src/errors.test.tsindex 5f6ff5e45532..088d8518b411 100644--- a/products/desktop/packages/shared/src/errors.test.ts+++ b/products/desktop/packages/shared/src/errors.test.ts@@ -124,6 +124,7 @@ describe("classifyGatewayLimitError", () => {"org_limit",],["Rate limit exceeded: User sustained rate limit exceeded", "org_limit"],+ ["Cloud usage limit reached", "org_limit"],])("classifies %j as %s", (message, expected) => {expect(classifyGatewayLimitError(message)).toBe(expected);});@@ -150,6 +151,7 @@ describe("classifyGatewayLimitError", () => {describe("classifyPromptFailure", () => {it.each([["Rate limit exceeded", undefined, "usage_limit", false],+ ["Cloud usage limit reached", undefined, "usage_limit", false],["API Error: 529 overloaded", undefined, "transient", true],["boom", "upstream_timeout", "transient", true],["Authentication required", undefined, "authentication", true],diff --git a/products/desktop/packages/shared/src/errors.ts b/products/desktop/packages/shared/src/errors.tsindex 24af060f924b..9191deb3ba52 100644--- a/products/desktop/packages/shared/src/errors.ts+++ b/products/desktop/packages/shared/src/errors.ts@@ -79,6 +79,7 @@ export type GatewayLimitCause = "model_gate" | "org_limit";const MODEL_GATE_PATTERNS = ["needs a paid posthog plan"] as const;const ORG_LIMIT_PATTERNS = [+ "cloud usage limit reached","reached its posthog desktop usage limit",// Older gateway deployments still send the pre-rename wording."reached its posthog code usage limit",diff --git a/products/desktop/packages/ui/src/features/billing/UsageLimitModal.stories.tsx b/products/desktop/packages/ui/src/features/billing/UsageLimitModal.stories.tsxnew file mode 100644index 000000000000..9951e6534611--- /dev/null+++ b/products/desktop/packages/ui/src/features/billing/UsageLimitModal.stories.tsx@@ -0,0 +1,39 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { UsageLimitModalContent } from "./UsageLimitModal";++const meta: Meta<typeof UsageLimitModalContent> = {+ title: "Billing/Usage limit modal",+ component: UsageLimitModalContent,+ args: {+ open: true,+ onDismiss: () => {},+ onAction: () => {},+ },+};++export default meta;+type Story = StoryObj<typeof UsageLimitModalContent>;++export const OrganizationAdmin: Story = {+ args: {+ content: {+ title: "Organization usage limit reached",+ description:+ "Your organization has reached its PostHog Desktop credit limit. Change the limit in Plan & usage to keep going.",+ actionLabel: "Open Plan & usage",+ dismissLabel: "Got it",+ },+ },+};++export const OrganizationMember: Story = {+ args: {+ content: {+ title: "Organization usage limit reached",+ description:+ "Your organization has reached its PostHog Desktop credit limit. Contact an organization administrator to change the limit.",+ actionLabel: null,+ dismissLabel: "Got it",+ },+ },+};diff --git a/products/desktop/packages/ui/src/features/billing/UsageLimitModal.tsx b/products/desktop/packages/ui/src/features/billing/UsageLimitModal.tsxindex 2f25a5451ac3..69f9cdd4f9c9 100644--- a/products/desktop/packages/ui/src/features/billing/UsageLimitModal.tsx+++ b/products/desktop/packages/ui/src/features/billing/UsageLimitModal.tsx@@ -1,13 +1,22 @@import { WarningCircle } from "@phosphor-icons/react";import { formatResetTime } from "@posthog/core/billing/usageDisplay";+import type { UsageLimitContent } from "@posthog/core/billing/usageLimitContent";import { usageLimitContent } from "@posthog/core/billing/usageLimitContent";+import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogTitle,+} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";-import { Button, Dialog, Flex, Text } from "@radix-ui/themes";import { useEffect } from "react";import { track } from "../../shell/analytics";import { openExternalUrl } from "../../shell/openExternal";import { getBillingUrl } from "../../utils/urls";import { useAuthStateValue } from "../auth/store";+import { useIsOrgAdmin } from "../auth/useOrgRole";import { useUsageLimitStore } from "./usageLimitStore";import { useUsage } from "./useUsage";@@ -17,6 +26,7 @@ export function UsageLimitModal() {const cause = useUsageLimitStore((s) => s.cause);const hide = useUsageLimitStore((s) => s.hide);const cloudRegion = useAuthStateValue((state) => state.cloudRegion);+ const { isAdmin } = useIsOrgAdmin();const { usage } = useUsage({ enabled: isOpen });useEffect(() => {@@ -32,6 +42,7 @@ export function UsageLimitModal() {cause,resetLabel: resetAt ? formatResetTime(resetAt) : null,subscribed: usage?.code_usage_subscribed,+ canManageBilling: isAdmin === true,});const handleAction = () => {@@ -45,40 +56,53 @@ export function UsageLimitModal() {};return (- <Dialog.Root open={isOpen}>- <Dialog.Content- maxWidth="400px"- onInteractOutside={(e) => e.preventDefault()}- onEscapeKeyDown={hide}- >- <Flex direction="column" gap="3">- <Flex align="center" gap="2">+ <UsageLimitModalContent+ open={isOpen}+ content={content}+ onDismiss={hide}+ onAction={handleAction}+ />+ );+}++export function UsageLimitModalContent({+ open,+ content,+ onDismiss,+ onAction,+}: {+ open: boolean;+ content: UsageLimitContent;+ onDismiss: () => void;+ onAction: () => void;+}) {+ return (+ <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onDismiss()}>+ <DialogContent className="sm:max-w-[400px]">+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2"><WarningCircle size={20} weight="bold" color="var(--red-9)" />- <Dialog.Title className="mb-0">{content.title}</Dialog.Title>- </Flex>- <Dialog.Description>- <Text color="gray" className="text-sm">- {content.description}- </Text>- </Dialog.Description>- <Flex justify="end" gap="3" mt="2">+ <DialogTitle className="mb-0">{content.title}</DialogTitle>+ </div>+ <DialogDescription className="text-(--gray-11) text-sm">+ {content.description}+ </DialogDescription>+ <DialogFooter className="border-t-0 bg-transparent"><Buttontype="button"- {...(content.actionLabel- ? { variant: "soft" as const, color: "gray" as const }- : {})}- onClick={hide}+ variant={content.actionLabel ? "outline" : "primary"}+ onClick={onDismiss}>{content.dismissLabel}</Button>{content.actionLabel && (- <Button type="button" onClick={handleAction}>+ <Button type="button" onClick={onAction}>{content.actionLabel}</Button>)}- </Flex>- </Flex>- </Dialog.Content>- </Dialog.Root>+ </DialogFooter>+ </div>+ </DialogContent>+ </Dialog>);}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 45f835acd26b..a46011a9d337 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2079,12 +2079,13 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(# queued repo-less run."github_read_access",# Loop provenance is stamped once at run creation (see loop_runs._create_loop_task_and_run)- # and drives loop bookkeeping in handle_loop_run_terminal. A run update must never be able- # to forge or repoint it, or a caller could steer terminal side effects at another loop.+ # and drives loop bookkeeping in handle_loop_run_terminal. The completion marker prevents+ # terminal bookkeeping from running twice. A caller must not be able to forge either."loop_id","loop_trigger_id","trigger_context","config_snapshot",+ "loop_terminal_bookkeeping_complete",# Stamped once at run creation. The review carve-outs read ai_stage="implementation" as proof# a run is self-driving, so a PATCHable value would forge that and unlock the bot/draft bypass."ai_stage",diff --git a/products/tasks/backend/logic/services/loop_runs.py b/products/tasks/backend/logic/services/loop_runs.pyindex a3cebe831709..e145db836800 100644--- a/products/tasks/backend/logic/services/loop_runs.py+++ b/products/tasks/backend/logic/services/loop_runs.py@@ -49,6 +49,8 @@ TRIGGER_CONTEXT_MAX_BYTES = 64 * 1024# the field in facade/loops.py::update_loop either way.DISABLED_REASON_USAGE_LIMITED = "usage_limited"DISABLED_REASON_REPEATED_FAILURES = "repeated_failures"+COMPUTE_BILLING_LIMIT_ERROR_TYPE = "ComputeBillingLimitError"+LOOP_TERMINAL_BOOKKEEPING_STATE_KEY = "loop_terminal_bookkeeping_complete"_NON_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS)_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)@@ -850,24 +852,30 @@ def _increment_consecutive_failures_and_maybe_pause(loop: Loop, *, error: str, d)-def handle_loop_run_terminal(task_run: TaskRun) -> None:+def handle_loop_run_terminal(task_run: TaskRun, *, error_type: str | None = None) -> None:"""Update loop bookkeeping when one of its runs reaches a terminal status.Resets `consecutive_failures` on success, increments it on failure/cancellation,auto-pausing the loop (and its schedules) at `LOOP_AUTO_PAUSE_THRESHOLD`. No-opfor runs that aren't loop-spawned or aren't yet terminal."""- state = task_run.state if isinstance(task_run.state, dict) else {}- loop_id = state.get("loop_id")- if not loop_id:- return- if task_run.status not in _TERMINAL_TASK_RUN_STATUSES:- return-- is_success = task_run.status == TaskRun.Status.COMPLETEDshould_pause = Falsewith transaction.atomic():+ locked_task_run = TaskRun.objects.select_for_update().filter(id=task_run.id).first()+ if locked_task_run is None or locked_task_run.status not in _TERMINAL_TASK_RUN_STATUSES:+ return+ state = locked_task_run.state if isinstance(locked_task_run.state, dict) else {}+ if state.get(LOOP_TERMINAL_BOOKKEEPING_STATE_KEY):+ return+ loop_id = state.get("loop_id")+ if not loop_id:+ return++ task_run = locked_task_run+ is_success = task_run.status == TaskRun.Status.COMPLETED+ is_billing_denial = error_type == COMPUTE_BILLING_LIMIT_ERROR_TYPE+# Scope the loop to the run's own team. `loop_id` lives in run state, which is# writable through the run-update endpoint; without this a caller in team B could# set their run's state loop_id to a team A loop and steer its bookkeeping,@@ -880,15 +888,28 @@ def handle_loop_run_terminal(task_run: TaskRun) -> None:loop.last_run_at = task_run.completed_at or django_timezone.now()loop.last_run_status = task_run.status- loop.last_error = None if is_success else task_run.error_message+ loop.last_error = (+ None+ if is_success+ else "Your organization has reached its PostHog Desktop credit limit."+ if is_billing_denial+ else task_run.error_message+ )loop.consecutive_failures = 0 if is_success else loop.consecutive_failures + 1update_fields = ["last_run_at", "last_run_status", "last_error", "consecutive_failures", "updated_at"]- if not is_success and loop.consecutive_failures >= LOOP_AUTO_PAUSE_THRESHOLD and loop.enabled:+ if is_billing_denial and loop.enabled:+ loop.enabled = False+ loop.disabled_reason = DISABLED_REASON_USAGE_LIMITED+ update_fields.extend(["enabled", "disabled_reason"])+ should_pause = True+ elif not is_success and loop.consecutive_failures >= LOOP_AUTO_PAUSE_THRESHOLD and loop.enabled:loop.enabled = Falseloop.disabled_reason = DISABLED_REASON_REPEATED_FAILURESupdate_fields.extend(["enabled", "disabled_reason"])should_pause = Trueloop.save(update_fields=update_fields)+ task_run.state = {**state, LOOP_TERMINAL_BOOKKEEPING_STATE_KEY: True}+ task_run.save(update_fields=["state", "updated_at"])if should_pause:pause_loop_schedules(loop)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex 09268ed5ab26..9f440a235da2 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -235,11 +235,7 @@ class TestUpdateTaskRunStatusActivity:assert len(completed) == 1@pytest.mark.django_db(transaction=True)- def test_terminal_transition_updates_loop_bookkeeping_exactly_once(self, activity_environment, test_task_run):- # This activity is how workflow-driven loop runs reach a terminal status, so it must- # drive loop bookkeeping (last_run_status, consecutive_failures -> auto-pause) — the- # HTTP PATCH path is never taken for these. A repeat of the same terminal update must- # not double-count.+ def test_terminal_retry_completes_loop_bookkeeping_exactly_once(self, activity_environment, test_task_run):loop = Loop(team=test_task_run.team,created_by=test_task_run.task.created_by,@@ -249,7 +245,9 @@ class TestUpdateTaskRunStatusActivity:)loop.save()test_task_run.state = {**(test_task_run.state or {}), "loop_id": str(loop.id)}- test_task_run.save(update_fields=["state"])+ test_task_run.status = TaskRun.Status.FAILED+ test_task_run.error_message = "sandbox crashed"+ test_task_run.save(update_fields=["state", "status", "error_message"])input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.FAILED, error_message="sandbox crashed"diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex f6a6f034d44a..7cefd0a1c303 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -120,18 +120,13 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:if input.timed_out_inactivity and old_status != input.status:task_run.task.soft_delete_if_unclaimed_prewarm(task_run)- # This activity is how workflow-driven runs (finish tool, failures, timeouts, cancellations)- # reach a terminal status, so loop bookkeeping must hook in here, not only in the HTTP PATCH- # path (facade.api.update_task_run). Guarded on the actual transition so repeats and the- # PATCH-then-activity dual write don't double-count consecutive_failures; swallowed so a- # bookkeeping failure never fails (and re-runs) the status write itself.- if old_status != input.status:+ if input.status in _TERMINAL_STATUSES:from products.tasks.backend.logic.services.loop_runs import ( # noqa: PLC0415 — breaks the loop_runs -> process_task -> activities import cyclehandle_loop_run_terminal,)try:- handle_loop_run_terminal(task_run)+ handle_loop_run_terminal(task_run, error_type=input.error_type)except Exception:activity.logger.warning(f"Failed loop terminal bookkeeping for run {task_run.id}", exc_info=True)diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 612ea41fa2ae..f2817dca76b7 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -1050,7 +1050,7 @@ class TestProcessTaskWorkflowUnit:"failed",error_message="Sandbox not in running state.",run_id="run-id",- error_type="ActivityError",+ error_type="SandboxNotRunningError",)async def test_run_skips_relay_when_sandbox_event_ingest_is_enabled(self, monkeypatch):diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 8d4e0848f512..ca47ad145985 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -1102,6 +1102,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):# the UI show the persisted message, so surface the cause instead.cause = e.cause if isinstance(e, temporalio.exceptions.ActivityError) else Nonecause_message = getattr(cause, "message", None) or (str(cause) if cause is not None else None)+ error_type = getattr(cause, "type", None) or type(e).__name__error_message = truncate_error_message(cause_message or str(e))if self._context:if self._current_progress_step is not None:@@ -1137,7 +1138,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):capture_analytics=False,)await self._update_task_run_status(- "failed", error_message=error_message, run_id=run_id, error_type=type(e).__name__+ "failed", error_message=error_message, run_id=run_id, error_type=error_type)if self._context:await self._post_slack_update()diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 2d1c239acf4b..8ebd8d50e86d 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -5173,6 +5173,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"provider": "anthropic","model": "claude-sonnet-5","reasoning_effort": "low",+ "loop_terminal_bookkeeping_complete": True,},)@@ -5226,6 +5227,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"provider": "openai","model": "claude-opus-4-8","reasoning_effort": "high",+ "loop_terminal_bookkeeping_complete": False,"scratch": "ok",}},@@ -5261,6 +5263,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["provider"] == "anthropic"assert run.state["model"] == "claude-sonnet-5"assert run.state["reasoning_effort"] == "low"+ assert run.state["loop_terminal_bookkeeping_complete"] is Trueassert run.state["scratch"] == "ok" # non-protected keys still merge# Nor can a caller remove a protected key to force a fallback or unguarded path.@@ -5286,6 +5289,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"provider","model","reasoning_effort",+ "loop_terminal_bookkeeping_complete","scratch",],},@@ -5313,6 +5317,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["provider"] == "anthropic" # protected key survives removalassert run.state["model"] == "claude-sonnet-5" # protected key survives removalassert run.state["reasoning_effort"] == "low" # protected key survives removal+ assert run.state["loop_terminal_bookkeeping_complete"] is Trueassert "scratch" not in run.state # non-protected key removed@patch("products.tasks.backend.facade.api.signal_workflow_completion")diff --git a/products/tasks/backend/tests/test_loop_runs.py b/products/tasks/backend/tests/test_loop_runs.pyindex 3d8a10c6b9d8..ee70a075ec78 100644--- a/products/tasks/backend/tests/test_loop_runs.py+++ b/products/tasks/backend/tests/test_loop_runs.py@@ -1021,6 +1021,21 @@ class TestHandleLoopRunTerminal(LoopRunsTestCase):{"task_id": str(task_run.task_id), "task_run_id": str(task_run.id), "status": TaskRun.Status.FAILED},)+ @patch(f"{LOOP_RUNS_MODULE}.dispatch_loop_event")+ @patch(f"{LOOP_RUNS_MODULE}.pause_loop_schedules")+ def test_compute_billing_denial_pauses_without_retrying(self, mock_pause, mock_dispatch):+ loop = self.create_loop(consecutive_failures=0)+ task_run = self.make_terminal_task_run(loop, status=TaskRun.Status.FAILED, error_message="backend detail")++ with self.captureOnCommitCallbacks(execute=True):+ handle_loop_run_terminal(task_run, error_type="ComputeBillingLimitError")++ loop.refresh_from_db()+ self.assertFalse(loop.enabled)+ self.assertEqual(loop.disabled_reason, DISABLED_REASON_USAGE_LIMITED)+ self.assertEqual(loop.last_error, "Your organization has reached its PostHog Desktop credit limit.")+ mock_pause.assert_called_once()+@patch(f"{LOOP_RUNS_MODULE}.dispatch_loop_event")@patch(f"{LOOP_RUNS_MODULE}.pause_loop_schedules")def test_failed_run_reaching_threshold_auto_pauses_the_loop(self, mock_pause, mock_dispatch):