: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(tasks): persist gateway-backed task run costs (#99986)
Oliver Brownefdffabc4f135
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.mdindex 04ec05e67da7..397c380a81e8 100644--- a/docs/internal/task-run-api.md+++ b/docs/internal/task-run-api.md@@ -42,6 +42,8 @@ Agent-sourced runs use the read-only MCP permission preset.Run state updates cannot change or remove the run source or base branch.The `state` field must be a JSON object.+Run responses omit internal cost accounting, including gateway request IDs.+## Event deliveryCloud runs send live events through event ingest. Clients can replay only events mirrored into the backend stream.diff --git a/posthog/urls.py b/posthog/urls.pyindex 2202a073fa1f..5e023cfec0d7 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -72,6 +72,7 @@ from products.slack_app.backend.views import (from products.streamlit_apps.backend.presentation.bridge_views import StreamlitBridgeViewfrom products.surveys.backend.api.survey import public_survey_pagefrom products.tasks.backend.facade.agent_proxy import agent_proxy_callback+from products.tasks.backend.presentation.views.gateway_generation_requests import gateway_generation_requestfrom products.user_interviews.backend.presentation.webhooks import start_call as user_interviews_start_callfrom products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSetfrom products.workflows.backend.api import hog_flow, hog_flow_template@@ -217,6 +218,10 @@ urlpatterns = ["internal/tasks/runs/<str:run_id>/agent-proxy-callback/",csrf_exempt(agent_proxy_callback),),+ path(+ "internal/teams/<int:team_id>/task_runs/<str:run_id>/generation_requests/<str:request_id>/",+ csrf_exempt(gateway_generation_request),+ ),# Internal SQLV2 run result callback (auth: signed callback token)path("internal/notebooks/runs/<str:run_id>/result/",diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.tsindex 39855a0a0cf4..e7f9f81e0bdf 100644--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts@@ -259,6 +259,7 @@ describe("AgentServer.configureEnvironment", () => {"x-posthog-property-team_id": "1","x-posthog-property-$ai_session_id": "task-abc","X-PostHog-Project-Id": "1",+ "X-PostHog-Task-Run-Id": "run-xyz",});});@@ -302,6 +303,7 @@ describe("AgentServer.configureEnvironment", () => {"x-posthog-property-task_snapshot_kind: filesystem","x-posthog-property-task_prewarmed: false","x-posthog-property-task_execution_environment: cloud",+ "X-PostHog-Task-Run-Id: run-xyz","X-PostHog-Project-Id: 1",].join("\n"),);@@ -499,7 +501,7 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {const parseBlob = (headerLines: string): Record<string, unknown> => {const prefix = "X-PostHog-Properties: ";expect(headerLines.startsWith(prefix)).toBe(true);- return JSON.parse(headerLines.slice(prefix.length));+ return JSON.parse(headerLines.slice(prefix.length).split("\n")[0]);};it("drops the product slug from the base URLs", () => {@@ -583,6 +585,12 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {expect(JSON.parse(env.openaiCustomHeaders?.["X-PostHog-Properties"] ?? "{}"),).toMatchObject(expected);+ expect(env.anthropicCustomHeaders).toContain(+ "X-PostHog-Task-Run-Id: run-1",+ );+ expect(env.openaiCustomHeaders).toMatchObject({+ "X-PostHog-Task-Run-Id": "run-1",+ });});it("emits attribution as one X-PostHog-Properties blob, not per-property headers", () => {diff --git a/products/desktop/packages/shared/src/posthog-property-headers.test.ts b/products/desktop/packages/shared/src/posthog-property-headers.test.tsindex d716f0028abc..69d6d11fc46b 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.test.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.test.ts@@ -32,6 +32,45 @@ describe("PostHog project headers", () => {});});+describe("task run headers", () => {+ it("uses task_run_id instead of task_id in record and line formats", () => {+ const properties = { task_id: "task-1", task_run_id: "run-1" };++ expect(buildPosthogPropertyHeaderRecord(properties)).toMatchObject({+ "X-PostHog-Task-Run-Id": "run-1",+ });+ expect(buildPosthogPropertyHeaderLines(properties)).toContain(+ "X-PostHog-Task-Run-Id: run-1",+ );+ expect(buildPosthogPropertiesHeaderRecord(properties)).toMatchObject({+ "X-PostHog-Task-Run-Id": "run-1",+ });+ expect(buildPosthogPropertiesHeaderLines(properties)).toContain(+ "X-PostHog-Task-Run-Id: run-1",+ );+ });++ it.each([undefined, null, "", false, 0])(+ "omits a task run header for %s",+ (taskRunId) => {+ const properties = { task_id: "task-1", task_run_id: taskRunId };++ expect(buildPosthogPropertyHeaderRecord(properties)).not.toHaveProperty(+ "X-PostHog-Task-Run-Id",+ );+ expect(buildPosthogPropertyHeaderLines(properties)).not.toContain(+ "X-PostHog-Task-Run-Id",+ );+ expect(buildPosthogPropertiesHeaderRecord(properties)).not.toHaveProperty(+ "X-PostHog-Task-Run-Id",+ );+ expect(buildPosthogPropertiesHeaderLines(properties)).not.toContain(+ "X-PostHog-Task-Run-Id",+ );+ },+ );+});+describe("buildPosthogPropertyHeaderRecord", () => {it("returns each property as an x-posthog-property-<key> entry", () => {expect(diff --git a/products/desktop/packages/shared/src/posthog-property-headers.ts b/products/desktop/packages/shared/src/posthog-property-headers.tsindex dfbaea817cab..7bb92ae24dca 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.ts@@ -3,6 +3,7 @@ export type PosthogPropertyValue = string | number | boolean | null | undefined;export type PosthogProperties = Record<string, PosthogPropertyValue>;export const POSTHOG_PROJECT_ID_HEADER = "X-PostHog-Project-Id";+export const POSTHOG_TASK_RUN_ID_HEADER = "X-PostHog-Task-Run-Id";/*** Make a value safe to embed in an HTTP header value. Only printable ASCII@@ -33,6 +34,11 @@ function buildEntries(properties: PosthogProperties): Array<[string, string]> {return entries;}+function taskRunIdHeader(properties: PosthogProperties): string | null {+ const taskRunId = properties.task_run_id;+ return typeof taskRunId === "string" ? sanitizeHeaderValue(taskRunId) : null;+}+/*** Build a `Record<string, string>` of `x-posthog-property-<name>` headers* suitable for `fetch()` init.headers. The LLM gateway lifts each header@@ -44,7 +50,11 @@ function buildEntries(properties: PosthogProperties): Array<[string, string]> {export function buildPosthogPropertyHeaderRecord(properties: PosthogProperties,): Record<string, string> {- return Object.fromEntries(buildEntries(properties));+ const taskRunId = taskRunIdHeader(properties);+ return {+ ...Object.fromEntries(buildEntries(properties)),+ ...(taskRunId ? { [POSTHOG_TASK_RUN_ID_HEADER]: taskRunId } : {}),+ };}/**@@ -56,7 +66,7 @@ export function buildPosthogPropertyHeaderRecord(export function buildPosthogPropertyHeaderLines(properties: PosthogProperties,): string {- return buildEntries(properties)+ return Object.entries(buildPosthogPropertyHeaderRecord(properties)).map(([key, value]) => `${key}: ${value}`).join("\n");}@@ -193,16 +203,21 @@ export function buildPosthogPropertiesHeaderRecord(properties: PosthogProperties,): Record<string, string> {const blob = buildPosthogPropertiesBlob(properties);- return blob ? { [POSTHOG_PROPERTIES_HEADER]: blob } : {};+ const taskRunId = taskRunIdHeader(properties);+ return {+ ...(blob ? { [POSTHOG_PROPERTIES_HEADER]: blob } : {}),+ ...(taskRunId ? { [POSTHOG_TASK_RUN_ID_HEADER]: taskRunId } : {}),+ };}/**- * {@link buildPosthogPropertiesBlob} as a single `key: value` line for+ * {@link buildPosthogPropertiesHeaderRecord} as `key: value` lines for* `ANTHROPIC_CUSTOM_HEADERS`, empty when there is nothing to send.*/export function buildPosthogPropertiesHeaderLines(properties: PosthogProperties,): string {- const blob = buildPosthogPropertiesBlob(properties);- return blob ? `${POSTHOG_PROPERTIES_HEADER}: ${blob}` : "";+ return Object.entries(buildPosthogPropertiesHeaderRecord(properties))+ .map(([key, value]) => `${key}: ${value}`)+ .join("\n");}diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 98a5d418cd65..e433ea644778 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -101,6 +101,7 @@ from products.tasks.backend.github_repository_access import ()from products.tasks.backend.logic.model_access import InvalidModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, pinned_run_allows_model+from products.tasks.backend.logic.services.gateway_usage import refresh_task_run_costfrom products.tasks.backend.logic.services.image_builder import (ensure_image_builder_task,is_custom_images_enabled,@@ -2605,6 +2606,10 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("pr_base_branch","stack_base_branch","github_credential_source",+ "token_cost",+ "token_cost_incomplete",+ "compute_cost",+ "unprocessed_request_ids",TASK_OWNERSHIP_VERSION_STATE_KEY,"pr_authorship_mode","repositories",@@ -3321,6 +3326,12 @@ def update_task_run(# (consecutive_failures would double-count). The workflow's status-update activity# applies the same guard on its side.if new_status in _TERMINAL_TASK_RUN_STATUSES and old_status != new_status:+ try:+ if run.environment == TaskRun.Environment.CLOUD:+ refresh_task_run_cost(run_id=run.id, team_id=run.team_id)+ run.refresh_from_db(fields=["state", "updated_at"])+ except Exception:+ logger.warning("task_run_cost_refresh_failed", extra={"run_id": str(run.id)}, exc_info=True)handle_loop_run_terminal(run)if new_status in _TERMINAL_TASK_RUN_STATUSES and old_status != new_status:@@ -6123,7 +6134,7 @@ def resume_task_run_in_cloud(run.environment = prior_environmentrun.completed_at = prior_completed_atrun.queued_at = prior_queued_at- run.state = prior_state+ run.restore_cloud_resume_state(prior_state)run.error_message = "Failed to start cloud workflow"run.save(update_fields=[diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.pyindex e12f40d827e3..ffbea082b6f1 100644--- a/products/tasks/backend/facade/billing.py+++ b/products/tasks/backend/facade/billing.py@@ -4,6 +4,8 @@ The usage reporter (posthog/tasks/usage_report.py) lives in the ``posthog`` moduwhich may only import ``products.tasks`` through the facade (see tach.toml)."""+from products.tasks.backend.facade.contracts import TaskRunCost+from products.tasks.backend.logic.services.gateway_usage import get_task_cost, get_task_run_costfrom products.tasks.backend.logic.services.sandbox_pricing import ComputeRateCardConfigurationErrorfrom products.tasks.backend.logic.services.sandbox_usage import (SandboxComputeUsageByTeam,@@ -23,6 +25,7 @@ from products.tasks.backend.logic.services.task_usage import (__all__ = ["ComputeRateCardConfigurationError",+ "TaskRunCost","SandboxComputeUsageByTeam","SandboxUsageByTeam","TaskUsage",@@ -34,4 +37,6 @@ __all__ = ["get_local_task_token_cost","get_task_sandbox_usage_by_team","get_task_usage",+ "get_task_run_cost",+ "get_task_cost",]diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 4511fb3e5b27..77079a7b4ab9 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -98,6 +98,14 @@ class WizardCloudRunDTO:started_at: datetime | None = None+@dataclass(frozen=True)+class TaskRunCost:+ """Provider costs in integer USD cents, or None while a source is unavailable or incomplete."""++ token_cost: int | None+ compute_cost: int | None++@dataclass(frozen=True)class TaskRunDTO:"""A single execution of a task.diff --git a/products/tasks/backend/facade/gateway.py b/products/tasks/backend/facade/gateway.pynew file mode 100644index 000000000000..bdb7ab123a81--- /dev/null+++ b/products/tasks/backend/facade/gateway.py@@ -0,0 +1,14 @@+from uuid import UUID++from products.tasks.backend.logic.services.gateway_usage import record_generation_request, schedule_gateway_usage+from products.tasks.backend.models import TaskRun+++def accept_generation_request(*, team_id: int, run_id: UUID, request_id: str) -> bool:+ try:+ recorded = record_generation_request(team_id=team_id, run_id=run_id, request_id=request_id)+ except TaskRun.DoesNotExist:+ return False+ if recorded:+ schedule_gateway_usage(team_id=team_id, run_id=run_id)+ return Truediff --git a/products/tasks/backend/logic/services/gateway_usage.py b/products/tasks/backend/logic/services/gateway_usage.pynew file mode 100644index 000000000000..0dabe4ba4896--- /dev/null+++ b/products/tasks/backend/logic/services/gateway_usage.py@@ -0,0 +1,318 @@+import re+import time+import asyncio+from collections.abc import Iterable+from datetime import timedelta+from decimal import ROUND_HALF_EVEN, Decimal+from functools import lru_cache+from typing import TYPE_CHECKING, Any+from uuid import UUID++from django.conf import settings+from django.db import transaction+from django.utils import timezone++import structlog+from asgiref.sync import async_to_sync++from posthog.dataclasses import frozen++from products.tasks.backend.facade.contracts import TaskRunCost+from products.tasks.backend.logic.services.sandbox_pricing import COMPUTE_RATE_CARDS, calculate_sandbox_compute_cost+from products.tasks.backend.models import SandboxSession, TaskRun++if TYPE_CHECKING:+ from temporalio.client import Client++logger = structlog.get_logger(__name__)+_REQUEST_ID = re.compile(r"[a-zA-Z0-9_-]{1,255}\Z")+_USD_AMOUNT = re.compile(r"[0-9]{1,12}(?:\.[0-9]{1,6})?\Z")+_PROCESSING_SECONDS = 10+++@frozen+class GatewayRequestCost:+ model: str+ provider: str+ cost_microusd: int+++@frozen+class _CostSources:+ token_cost_microusd: int | None+ compute_cost_usd: Decimal | None++ def as_contract(self) -> TaskRunCost:+ return TaskRunCost(+ token_cost=_cents(Decimal(self.token_cost_microusd) / 1_000_000)+ if self.token_cost_microusd is not None+ else None,+ compute_cost=_cents(self.compute_cost_usd) if self.compute_cost_usd is not None else None,+ )+++def _locked_run(run_id: UUID | str, team_id: int) -> TaskRun:+ return TaskRun.objects.select_for_update().get(id=run_id, team_id=team_id)+++def gateway_usage_enabled(run: TaskRun) -> bool:+ state = run.state or {}+ return (+ run.environment == TaskRun.Environment.CLOUD+ and isinstance(state.get("unprocessed_request_ids"), list)+ and isinstance(state.get("token_cost"), dict)+ )+++def _save_accounting_state(run: TaskRun) -> None:+ # Accounting can finish after completion; it must not emit completion signals again.+ # It also leaves `updated_at` alone, because recency gauges and stale-run sweeps read it.+ TaskRun.objects.filter(id=run.id, team_id=run.team_id).update(state=run.state)+++def record_gateway_routing(*, run_id: UUID | str, team_id: int, uses_gateway: bool) -> None:+ with transaction.atomic():+ run = _locked_run(run_id, team_id)+ if run.environment != TaskRun.Environment.CLOUD:+ raise ValueError("Gateway cost requires a cloud run")+ state = dict(run.state or {})+ if uses_gateway:+ state.setdefault("unprocessed_request_ids", [])+ state.setdefault("token_cost", {})+ else:+ state["token_cost_incomplete"] = True+ if state == run.state:+ return+ run.state = state+ _save_accounting_state(run)+++def _cost_buckets(state: dict[str, Any]) -> Iterable[dict[str, Any]]:+ models = state.get("token_cost")+ if not isinstance(models, dict):+ return+ for providers in models.values():+ if isinstance(providers, dict):+ for bucket in providers.values():+ if isinstance(bucket, dict):+ yield bucket+++def _processed_gateway_request_ids(state: dict[str, Any]) -> set[str]:+ return {+ request_id+ for bucket in _cost_buckets(state)+ for request_id in bucket.get("request_ids", [])+ if isinstance(request_id, str)+ }+++def record_generation_request(*, team_id: int, run_id: UUID, request_id: str) -> bool:+ with transaction.atomic():+ run = _locked_run(run_id, team_id)+ if run.environment != TaskRun.Environment.CLOUD:+ return False+ state = dict(run.state or {})+ pending = state.get("unprocessed_request_ids")+ if not isinstance(pending, list):+ pending = []+ if request_id not in pending and request_id not in _processed_gateway_request_ids(state):+ pending = [*pending, request_id]+ state["unprocessed_request_ids"] = pending+ state.setdefault("token_cost", {})+ if state == run.state:+ return True+ run.state = state+ _save_accounting_state(run)+ return True+++def _pending_ids(state: dict[str, Any]) -> list[str]:+ return list(+ dict.fromkeys(+ value+ for value in state.get("unprocessed_request_ids", [])+ if isinstance(value, str) and _REQUEST_ID.fullmatch(value)+ )+ )+++def process_pending_gateway_usage(*, run_id: UUID, team_id: int, limit: int = 20) -> TaskRunCost:+ with transaction.atomic():+ run = _locked_run(run_id, team_id)+ state = run.state or {}+ if not gateway_usage_enabled(run):+ return _cost_sources(run).as_contract()+ pending = _pending_ids(state)[:limit]+ deadline = time.monotonic() + _PROCESSING_SECONDS+ for request_id in pending:+ if time.monotonic() >= deadline:+ break+ request_cost = async_to_sync(_fetch_gateway_cost)(request_id)+ with transaction.atomic():+ run = _locked_run(run_id, team_id)+ state = dict(run.state or {})+ remaining = _pending_ids(state)+ if request_id not in remaining:+ continue+ remaining.remove(request_id)+ processed = _processed_gateway_request_ids(state)+ if request_id not in processed:+ if request_cost is None:+ # A missing response must not block the rest of the queue.+ remaining.append(request_id)+ else:+ providers = state["token_cost"].setdefault(request_cost.model, {})+ bucket = providers.setdefault(request_cost.provider, {})+ bucket["cost_microusd"] = bucket.get("cost_microusd", 0) + request_cost.cost_microusd+ bucket["request_ids"] = [*bucket.get("request_ids", []), request_id]+ state["unprocessed_request_ids"] = remaining+ run.state = state+ _save_accounting_state(run)+ return refresh_task_run_cost(run_id=run_id, team_id=team_id)+++def refresh_task_run_cost(*, run_id: UUID, team_id: int) -> TaskRunCost:+ with transaction.atomic():+ run = _locked_run(run_id, team_id)+ cost = _cost_sources(run).as_contract()+ state = dict(run.state or {})+ if "compute_cost" not in state or state["compute_cost"] != cost.compute_cost:+ state["compute_cost"] = cost.compute_cost+ run.state = state+ _save_accounting_state(run)+ return cost+++def get_task_run_cost(*, run_id: UUID, team_id: int) -> TaskRunCost:+ return _cost_sources(TaskRun.objects.get(id=run_id, team_id=team_id)).as_contract()+++def get_task_cost(*, team_id: int, task_id: UUID) -> TaskRunCost:+ runs = list(TaskRun.objects.filter(team_id=team_id, task_id=task_id))+ if not runs:+ return TaskRunCost(token_cost=None, compute_cost=None)+ sessions_by_run: dict[UUID, list[SandboxSession]] = {}+ for session in SandboxSession.objects.for_team(team_id).filter(task_run__in=runs):+ sessions_by_run.setdefault(session.task_run_id, []).append(session)+ sources = [_cost_sources(run, sessions=sessions_by_run.get(run.id, [])) for run in runs]+ return _CostSources(+ token_cost_microusd=None+ if any(s.token_cost_microusd is None for s in sources)+ else sum(s.token_cost_microusd or 0 for s in sources),+ compute_cost_usd=None+ if any(s.compute_cost_usd is None for s in sources)+ else sum((s.compute_cost_usd or Decimal(0) for s in sources), Decimal(0)),+ ).as_contract()+++async def _fetch_gateway_cost(request_id: str) -> GatewayRequestCost | None:+ import aiohttp # noqa: PLC0415 - keeps aiohttp off Django's startup path++ base_url = (settings.SANDBOX_AI_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")+ mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY+ if not base_url or not mint_key:+ return None+ try:+ async with (+ aiohttp.ClientSession(trust_env=True) as session,+ session.get(+ f"{base_url}/v1/usage/{request_id}",+ headers={"Authorization": f"Bearer {mint_key}"},+ timeout=aiohttp.ClientTimeout(total=15, connect=2, sock_read=3),+ allow_redirects=False,+ ) as response,+ ):+ if response.status != 200:+ logger.warning("task_gateway_usage.cost_pending", status_code=response.status)+ return None+ body = await response.json()+ if not isinstance(body, dict) or body.get("request_id") != request_id:+ return None+ amount = body.get("cost_usd")+ model, provider = body.get("model") or "unknown", body.get("provider") or "unknown"+ if (+ not isinstance(amount, str)+ or not _USD_AMOUNT.fullmatch(amount)+ or not isinstance(model, str)+ or len(model) > 255+ or not isinstance(provider, str)+ or len(provider) > 255+ ):+ return None+ return GatewayRequestCost(model=model, provider=provider, cost_microusd=int(Decimal(amount) * 1_000_000))+ except (aiohttp.ClientError, TimeoutError, ValueError, TypeError):+ logger.warning("task_gateway_usage.lookup_failed")+ return None+++def _cost_sources(run: TaskRun, *, sessions: list[SandboxSession] | None = None) -> _CostSources:+ return _CostSources(+ token_cost_microusd=sum(bucket.get("cost_microusd", 0) for bucket in _cost_buckets(run.state or {}))+ if gateway_usage_enabled(run)+ and not (run.state or {}).get("token_cost_incomplete")+ and not (run.state or {}).get("unprocessed_request_ids")+ else None,+ compute_cost_usd=_compute_cost_source(run, sessions=sessions),+ )+++def _compute_cost_source(run: TaskRun, *, sessions: list[SandboxSession] | None = None) -> Decimal | None:+ if run.environment != TaskRun.Environment.CLOUD or not COMPUTE_RATE_CARDS:+ return None+ if sessions is None:+ sessions = list(SandboxSession.objects.for_team(run.team_id).filter(task_run=run))+ if not sessions:+ return None+ now = timezone.now()+ try:+ return sum(+ (+ calculate_sandbox_compute_cost(+ session, COMPUTE_RATE_CARDS[0].effective_at, now, calculated_at=now, rate_cards=COMPUTE_RATE_CARDS+ ).total_cost_usd+ for session in sessions+ ),+ Decimal(0),+ )+ except ValueError:+ return None+++def _cents(value: Decimal) -> int:+ return int((value * 100).to_integral_value(rounding=ROUND_HALF_EVEN))+++@lru_cache(maxsize=1)+def _gateway_usage_client(loop: asyncio.AbstractEventLoop) -> asyncio.Task["Client"]:+ from posthog.temporal.common.client import async_connect # noqa: PLC0415 - keeps Temporal off Django's startup path++ # ASGI requests share a loop; a client must not cross into a different loop.+ return loop.create_task(asyncio.wait_for(async_connect(), timeout=5))+++async def _schedule_gateway_usage(*, run_id: UUID, team_id: int) -> None:+ from temporalio.common import WorkflowIDReusePolicy # noqa: PLC0415 - keeps Temporal off Django's startup path++ from products.tasks.backend.temporal.gateway_usage import ( # noqa: PLC0415 — avoids loading workflows during Django startup+ GatewayUsageInput,+ )++ try:+ client = await asyncio.shield(_gateway_usage_client(asyncio.get_running_loop()))+ except Exception:+ _gateway_usage_client.cache_clear()+ raise+ await client.start_workflow(+ "task-run-gateway-usage",+ GatewayUsageInput(run_id=str(run_id), team_id=team_id),+ id=f"task-run-gateway-usage-{team_id}-{run_id}",+ task_queue=settings.TASKS_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ start_signal="requests_available",+ rpc_timeout=timedelta(seconds=5),+ )+++def schedule_gateway_usage(*, run_id: UUID, team_id: int) -> None:+ async_to_sync(_schedule_gateway_usage)(run_id=run_id, team_id=team_id)diff --git a/products/tasks/backend/logic/services/workflow_dispatch.py b/products/tasks/backend/logic/services/workflow_dispatch.pyindex 5912944aae07..1252c3aede05 100644--- a/products/tasks/backend/logic/services/workflow_dispatch.py+++ b/products/tasks/backend/logic/services/workflow_dispatch.py@@ -434,7 +434,7 @@ def mark_dead(dispatch_id: Any, instance_id: str, error: str, reason: str = "payrun.environment = snapshot.environmentrun.completed_at = datetime.fromisoformat(snapshot.completed_at) if snapshot.completed_at else Nonerun.queued_at = datetime.fromisoformat(snapshot.queued_at) if snapshot.queued_at else None- run.state = snapshot.state+ run.restore_cloud_resume_state(snapshot.state)run.error_message = "Failed to start cloud workflow"else:from products.tasks.backend.temporal.client import _terminalize_unstarted_task_run # noqa: PLC0415diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex ea169530f0d3..2fbecfe8167d 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2553,6 +2553,28 @@ class TaskRun(models.Model):task_created_by_id=self.task.created_by_id,)+ _CLOUD_RESUME_CLEARED_STATE_KEYS = (+ "pending_user_message",+ "pending_user_artifact_ids",+ "pending_user_message_id",+ "pending_user_message_ts",+ "sandbox_id",+ "sandbox_url",+ "sandbox_jwt_kid",+ "sandbox_connect_token",+ "sandbox_backend",+ )++ def restore_cloud_resume_state(self, prior_state: dict[str, Any]) -> None:+ # Accounting and callbacks can update unrelated state while a restart is dispatched.+ state = dict(self.state or {})+ for key in ("same_run_resume", "mode", *self._CLOUD_RESUME_CLEARED_STATE_KEYS):+ if key in prior_state:+ state[key] = prior_state[key]+ else:+ state.pop(key, None)+ self.state = state+def prepare_for_cloud_resume(self) -> None:"""Restart this cloud run from its existing log and sandbox snapshot.@@ -2574,18 +2596,11 @@ class TaskRun(models.Model):prior_snapshot_mount_path = state.get("snapshot_mount_path")state["same_run_resume"] = Truestate["mode"] = "interactive"- state.pop("pending_user_message", None)- state.pop("pending_user_artifact_ids", None)- state.pop("pending_user_message_id", None)- state.pop("pending_user_message_ts", None)- state.pop("sandbox_id", None)- state.pop("sandbox_url", None)- state.pop("sandbox_jwt_kid", None)- state.pop("sandbox_connect_token", None)# Drop the provider stamp because the resumed run re-resolves its backend from# scratch, so a stale `hogland` must not survive to outrank the EU guard, the# Modal-only fallbacks, or the flag kill switch on the next context resolution.- state.pop("sandbox_backend", None)+ for key in self._CLOUD_RESUME_CLEARED_STATE_KEYS:+ state.pop(key, None)self.state = statelogger.info(diff --git a/products/tasks/backend/presentation/views/gateway_generation_requests.py b/products/tasks/backend/presentation/views/gateway_generation_requests.pynew file mode 100644index 000000000000..1a84389781e2--- /dev/null+++ b/products/tasks/backend/presentation/views/gateway_generation_requests.py@@ -0,0 +1,58 @@+import re+import hmac+import json+from uuid import UUID++from django.conf import settings+from django.http import HttpRequest, HttpResponse, JsonResponse++from posthog.models.project_secret_api_key import find_project_secret_api_key++from products.tasks.backend.facade.gateway import accept_generation_request++_REQUEST_ID = re.compile(r"[A-Za-z0-9_-]{1,255}\Z")+++def gateway_generation_request(request: HttpRequest, team_id: int, run_id: str, request_id: str) -> HttpResponse:+ if request.method != "POST":+ return JsonResponse({"error": "Method not allowed"}, status=405)++ expected_token = settings.AI_GATEWAY_INTERNAL_TOKEN or ""+ authorization = request.headers.get("Authorization", "")+ prefix = "Bearer "+ token = authorization[len(prefix) :] if authorization.startswith(prefix) else ""+ if not expected_token or not hmac.compare_digest(token.encode(), expected_token.encode()):+ return JsonResponse({"error": "Invalid service credential"}, status=401)++ wallet_header = request.headers.get("X-PostHog-Gateway-Team-Id", "")+ try:+ wallet_team_id = int(wallet_header)+ except ValueError:+ return JsonResponse({"error": "Invalid gateway team ID"}, status=400)+ if wallet_team_id <= 0:+ return JsonResponse({"error": "Invalid gateway team ID"}, status=400)++ if wallet_team_id != team_id:+ mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY+ mint_key_record = find_project_secret_api_key(mint_key) if mint_key else None+ if wallet_team_id != (mint_key_record.team_id if mint_key_record else None):+ return JsonResponse({"error": "Gateway team cannot fund this task run"}, status=403)++ try:+ parsed_run_id = UUID(run_id)+ except ValueError:+ return JsonResponse({"error": "Invalid task run ID"}, status=400)+ if str(parsed_run_id) != run_id or _REQUEST_ID.fullmatch(request_id) is None:+ return JsonResponse({"error": "Invalid generation request ID"}, status=400)++ if request.body.strip():+ try:+ body = json.loads(request.body)+ except (json.JSONDecodeError, UnicodeDecodeError):+ return JsonResponse({"error": "Invalid request body"}, status=400)+ if body != {}:+ return JsonResponse({"error": "Invalid request body"}, status=400)++ if not accept_generation_request(team_id=team_id, run_id=parsed_run_id, request_id=request_id):+ return JsonResponse({"error": "Task run not found"}, status=404)+ return HttpResponse(status=204)diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 509cbecd874a..8341c8dc69e3 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -11,6 +11,7 @@ from .create_snapshot.activities import (setup_repository as snapshot_setup_repository,)from .create_snapshot.workflow import CreateSnapshotForRepositoryWorkflow+from .gateway_usage import TaskRunGatewayUsageWorkflow, reconcile_gateway_usagefrom .loops import RunLoopWorkflow, run_loop_trigger_activityfrom .process_task.activities import (await_agent_server_ready,@@ -67,6 +68,7 @@ from .process_task.workflow import ProcessTaskWorkflowfrom .slack_relay import PostHogCodeAgentRelayWorkflow, relay_slack_messageWORKFLOWS = [+ TaskRunGatewayUsageWorkflow,ProcessTaskWorkflow,SlackAgentDesignRelayWorkflow,CreateSnapshotForRepositoryWorkflow,@@ -77,6 +79,7 @@ WORKFLOWS = []ACTIVITIES = [+ reconcile_gateway_usage,# process_task activitiesget_task_processing_context,prepare_sandbox_for_repository,diff --git a/products/tasks/backend/temporal/gateway_usage.py b/products/tasks/backend/temporal/gateway_usage.pynew file mode 100644index 000000000000..27c0212c8556--- /dev/null+++ b/products/tasks/backend/temporal/gateway_usage.py@@ -0,0 +1,100 @@+from dataclasses import replace+from datetime import datetime, timedelta+from uuid import UUID++from temporalio import activity, workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityError++from posthog.dataclasses import frozen+from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from posthog.temporal.common.utils import asyncify++ from products.tasks.backend.logic.services.gateway_usage import process_pending_gateway_usage+ from products.tasks.backend.models import TaskRun+++@frozen+class GatewayUsageInput:+ run_id: str+ team_id: int+ retry_until: datetime | None = None+++@asyncify+def reconcile_gateway_usage(input: GatewayUsageInput) -> int:+ try:+ process_pending_gateway_usage(run_id=UUID(input.run_id), team_id=input.team_id)+ state = TaskRun.objects.get(id=input.run_id, team_id=input.team_id).state or {}+ return len(state.get("unprocessed_request_ids", []))+ except TaskRun.DoesNotExist:+ return 0++[email protected](name="task-run-gateway-usage")+class TaskRunGatewayUsageWorkflow(PostHogWorkflow):+ inputs_cls = GatewayUsageInput++ def __init__(self) -> None:+ self._wakeups = 0+ self._retry_until: datetime | None = None++ @workflow.signal+ def requests_available(self) -> None:+ self._wakeups += 1+ self._retry_until = workflow.now() + timedelta(days=1)++ @workflow.run+ async def run(self, input: GatewayUsageInput) -> None:+ self._retry_until = max(+ self._retry_until or workflow.now(), input.retry_until or workflow.now() + timedelta(days=1)+ )+ delay = 30+ pending: int | None = None+ while workflow.now() < self._retry_until:+ wakeups = self._wakeups+ previous_pending = pending+ remaining = self._retry_until - workflow.now()+ try:+ pending = await workflow.execute_activity(+ reconcile_gateway_usage,+ input,+ start_to_close_timeout=min(timedelta(seconds=30), remaining),+ schedule_to_close_timeout=remaining,+ retry_policy=RetryPolicy(maximum_interval=timedelta(minutes=5)),+ )+ except ActivityError:+ pending = None+ if pending == 0 and wakeups == self._wakeups:+ return+ if workflow.now() >= self._retry_until:+ break++ # Backoff is for usage the gateway has not settled. A pass that settled usage runs the next batch at once.+ settled_usage = pending is not None and previous_pending is not None and pending < previous_pending+ if settled_usage:+ delay = 30+ else:++ def has_new_requests(wakeups: int = wakeups) -> bool:+ return self._wakeups != wakeups++ try:+ await workflow.wait_condition(+ has_new_requests,+ timeout=min(timedelta(seconds=delay), self._retry_until - workflow.now()),+ )+ except TimeoutError:+ pass+ delay = 30 if self._wakeups != wakeups else min(delay * 2, 300)+ if workflow.info().is_continue_as_new_suggested():+ workflow.continue_as_new(replace(input, retry_until=self._retry_until))++ # A 404 can be unsettled or permanently unpriced; keep the IDs for recovery.+ workflow.logger.warning(+ "task_gateway_usage.retries_exhausted",+ extra={"run_id": input.run_id, "team_id": input.team_id, "pending": pending},+ )diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.pyindex e97e3772a734..923eceae9c5d 100644--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py@@ -1,11 +1,13 @@import loggingfrom dataclasses import dataclass+from uuid import UUIDfrom temporalio import activityfrom posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.exceptions import SandboxNotFoundError+from products.tasks.backend.logic.services.gateway_usage import refresh_task_run_costfrom products.tasks.backend.logic.services.sandbox import get_sandbox_class_for_sandbox_idfrom products.tasks.backend.logic.services.sandbox_usage import (close_sandbox_session,@@ -46,15 +48,23 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:cpu_usage_usec = Nonebilled_cpu_usage_usec = Nonecpu_usage_measured_at = None+ run_id: UUID | None = None+ cleanup_error: Exception | None = None+ if input.run_id:+ try:+ run_id = UUID(input.run_id)+ except ValueError:+ logger.warning(+ "cleanup_sandbox_gateway_accounting_lookup_failed", extra={"run_id": input.run_id}, exc_info=True+ )try:sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)except SandboxNotFoundError:stream_completion_safe = Truesandbox = None- except Exception:+ except Exception as error:logger.warning("cleanup_sandbox_get_by_id_failed", extra={"sandbox_id": input.sandbox_id}, exc_info=True)- if strict_cleanup:- raise+ cleanup_error = errorsandbox = Noneif sandbox is not None:@@ -79,21 +89,11 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:try:sandbox.destroy()stream_completion_safe = True- except Exception:+ except Exception as error:logger.warning("cleanup_sandbox_destroy_failed", extra={"sandbox_id": input.sandbox_id}, exc_info=True)- if strict_cleanup:- close_sandbox_session(- input.sandbox_id,- reason=SandboxSession.EndedReason.CLEANUP,- cpu_usage_usec=cpu_usage_usec,- billed_cpu_usage_usec=billed_cpu_usage_usec,- cpu_usage_measured_at=cpu_usage_measured_at,- )- raise+ cleanup_error = error- # Best-effort usage-ledger end stamp (swallows its own failures). Stamped even when- # destroy failed or the sandbox was already gone: the TTL kills any undead sandbox- # anyway, and the ledger prefers a slightly early end over an open-ended row.+ # Costs after failed cleanup are platform overhead, not task costs.close_sandbox_session(input.sandbox_id,reason=SandboxSession.EndedReason.CLEANUP,@@ -102,9 +102,33 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:cpu_usage_measured_at=cpu_usage_measured_at,)- if input.run_id and stream_completion_safe:+ accounting_run: TaskRun | None = None+ if run_id is not None:+ try:+ run = TaskRun.objects.filter(id=run_id).only("id", "team_id", "environment").first()+ if run is not None and run.environment == TaskRun.Environment.CLOUD:+ accounting_run = run+ except Exception:+ logger.warning(+ "cleanup_sandbox_gateway_accounting_lookup_failed", extra={"run_id": input.run_id}, exc_info=True+ )++ if accounting_run is not None:+ try:+ refresh_task_run_cost(run_id=accounting_run.id, team_id=accounting_run.team_id)+ except Exception:+ logger.warning(+ "cleanup_sandbox_task_run_cost_refresh_failed",+ extra={"run_id": str(accounting_run.id)},+ exc_info=True,+ )++ if cleanup_error is not None and strict_cleanup:+ raise cleanup_error++ if run_id is not None and stream_completion_safe:try:- TaskRun.clear_sandbox_connection_state_atomic(input.run_id, input.sandbox_id)+ TaskRun.clear_sandbox_connection_state_atomic(run_id, input.sandbox_id)except TaskRun.DoesNotExist:passdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.pyindex 3399ef8dd23c..cf552bec6460 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py@@ -2,14 +2,24 @@ import osimport timeimport uuidimport threading+from contextlib import nullcontext+from datetime import timedeltaimport pytest+from unittest.mock import patch++from django.db import OperationalError+from django.utils import timezonefrom asgiref.sync import async_to_sync+from pytest_mock import MockerFixturefrom products.tasks.backend.exceptions import SandboxNotFoundError+from products.tasks.backend.facade.billing import get_task_run_cost+from products.tasks.backend.logic.services.gateway_usage import record_gateway_routingfrom products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key+from products.tasks.backend.models import SandboxSession, TaskRunfrom products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import (CleanupSandboxInput,cleanup_sandbox,@@ -80,46 +90,177 @@ def test_cleanup_sandbox_requests_agent_server_shutdown_when_completing_stream(asandbox.destroy.assert_called_once_with()+def accounting_session(test_task_run):+ record_gateway_routing(run_id=test_task_run.id, team_id=test_task_run.team_id, uses_gateway=True)+ now = timezone.now()+ return SandboxSession.objects.for_team(test_task_run.team_id).create(+ team_id=test_task_run.team_id,+ task_run=test_task_run,+ sandbox_id="sandbox-123",+ cpu_cores=2,+ memory_gb=4,+ ttl_seconds=600,+ created_at=now - timedelta(minutes=2),+ ttl_expires_at=now + timedelta(minutes=8),+ user_attributed_at=now - timedelta(minutes=2),+ )++@pytest.mark.django_db-def test_cleanup_sandbox_retries_when_final_destroy_fails(activity_environment, mocker):- run_id = str(uuid.uuid4())+ "environment,uses_gateway,lookup_fails,strict",+ [+ (TaskRun.Environment.CLOUD, True, False, True),+ (TaskRun.Environment.CLOUD, False, False, True),+ (TaskRun.Environment.LOCAL, False, False, True),+ (TaskRun.Environment.CLOUD, True, True, True),+ (TaskRun.Environment.CLOUD, True, False, False),+ ],+)+def test_cleanup_sandbox_closes_session_after_cleanup_error(+ mocker: MockerFixture,+ test_task_run: TaskRun,+ accounting_session: SandboxSession,+ environment: TaskRun.Environment,+ uses_gateway: bool,+ lookup_fails: bool,+ strict: bool,+) -> None:+ if not uses_gateway:+ test_task_run.state = {}+ test_task_run.environment = environment+ test_task_run.save(update_fields=["state", "environment"])sandbox = mocker.Mock(id="sandbox-123")sandbox.read_cpu_usage_usec.return_value = 12_345_678sandbox.read_billed_cpu_usage_usec.return_value = 15_000_000- sandbox.destroy.side_effect = RuntimeError("destroy failed")- mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)- close_session = mocker.patch(- "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.close_sandbox_session"+ sandbox.destroy.side_effect = RuntimeError("cleanup failed")+ mocker.patch.object(+ Sandbox,+ "get_by_id",+ side_effect=RuntimeError("cleanup failed") if lookup_fails else None,+ return_value=sandbox,)publish_complete = mocker.patch("products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete")+ closed_at = timezone.now()++ for attempt in range(2):+ with patch("django.utils.timezone.now", return_value=closed_at + timedelta(minutes=attempt)):+ with pytest.raises(RuntimeError, match="cleanup failed") if strict else nullcontext():+ cleanup_sandbox_now(+ CleanupSandboxInput(+ sandbox_id="sandbox-123",+ run_id=str(test_task_run.id),+ complete_stream_on_cleanup=strict,+ ),+ )+ accounting_session.refresh_from_db()+ assert accounting_session.ended_at == closed_at+ if environment == TaskRun.Environment.CLOUD:+ test_task_run.refresh_from_db()+ assert (+ test_task_run.state["compute_cost"]+ == get_task_run_cost(run_id=test_task_run.id, team_id=test_task_run.team_id).compute_cost+ )++ assert sandbox.destroy.call_count == (0 if lookup_fails else 2)+ if not lookup_fails:+ assert accounting_session.provider_cpu_usage_usec == 12_345_678+ assert accounting_session.provider_billed_cpu_usage_usec == 15_000_000+ publish_complete.assert_not_called()+- with pytest.raises(RuntimeError, match="destroy failed"):- async_to_sync(activity_environment.run)(- cleanup_sandbox,- CleanupSandboxInput(- sandbox_id="sandbox-123",- run_id=run_id,- complete_stream_on_cleanup=True,- ),+def test_cleanup_sandbox_destroys_before_accounting_lookup(+ mocker: MockerFixture, test_task_run: TaskRun, accounting_session: SandboxSession+) -> None:+ sandbox = mocker.Mock(id="sandbox-123")+ mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)++ destroyed_at_lookup: list[bool] = []++ def unavailable(*args: object, **kwargs: object) -> None:+ destroyed_at_lookup.append(sandbox.destroy.called)+ raise OperationalError("unavailable")++ with patch.object(TaskRun.objects, "filter", side_effect=unavailable):+ cleanup_sandbox_now(CleanupSandboxInput(sandbox_id="sandbox-123", run_id=str(test_task_run.id)))++ sandbox.destroy.assert_called_once_with()+ assert destroyed_at_lookup == [True]+ accounting_session.refresh_from_db()+ assert accounting_session.ended_at is not None++[email protected]("complete_stream,uses_gateway", [(False, True), (True, True), (True, False)])+def test_cleanup_sandbox_persists_compute_without_waiting_for_gateway_usage(+ mocker, test_task_run, accounting_session, complete_stream, uses_gateway+):+ test_task_run.refresh_from_db()+ test_task_run.state["unprocessed_request_ids"] = ["pending-request"]+ if not uses_gateway:+ test_task_run.state = {"token_cost_incomplete": True}+ test_task_run.save(update_fields=["state"])+ sandbox = mocker.Mock(id="sandbox-123")+ sandbox.stop_agent_server.return_value.exit_code = 0+ sandbox.read_cpu_usage_usec.return_value = None+ sandbox.read_billed_cpu_usage_usec.return_value = None+ mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)+ gateway_lookup = mocker.patch("aiohttp.ClientSession._request")++ def publish_complete(*_args, **_kwargs):+ test_task_run.refresh_from_db()+ assert (+ test_task_run.state["compute_cost"]+ == get_task_run_cost(run_id=test_task_run.id, team_id=test_task_run.team_id).compute_cost)+ assert test_task_run.state["compute_cost"] > 0+ return True++ publish = mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete",+ side_effect=publish_complete,+ )+ cleanup_sandbox_now(+ CleanupSandboxInput(+ sandbox_id="sandbox-123", run_id=str(test_task_run.id), complete_stream_on_cleanup=complete_stream+ ),+ )sandbox.destroy.assert_called_once_with()- sandbox.execute.assert_not_called()- close_session.assert_called_once_with(- "sandbox-123",- reason="cleanup",- cpu_usage_usec=12_345_678,- billed_cpu_usage_usec=15_000_000,- cpu_usage_measured_at=mocker.ANY,+ assert sandbox.stop_agent_server.call_count == int(complete_stream)+ assert publish.call_count == int(complete_stream)+ gateway_lookup.assert_not_called()+ accounting_session.refresh_from_db()+ assert accounting_session.ended_at is not None+ test_task_run.refresh_from_db()+ assert test_task_run.state["compute_cost"] > 0+ if uses_gateway:+ assert test_task_run.state["unprocessed_request_ids"] == ["pending-request"]+ else:+ assert get_task_run_cost(run_id=test_task_run.id, team_id=test_task_run.team_id).token_cost is None+++def test_cleanup_sandbox_ignores_invalid_optional_run_id(activity_environment, mocker):+ sandbox = mocker.Mock(id="sandbox-123")+ mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)++ async_to_sync(activity_environment.run)(+ cleanup_sandbox,+ CleanupSandboxInput(sandbox_id="sandbox-123", run_id="not-a-uuid"),)- publish_complete.assert_not_called()++ sandbox.destroy.assert_called_once_with()@pytest.mark.django_db@pytest.mark.parametrize("current_sandbox", ["sandbox-123", "sandbox-replacement"])-def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run, current_sandbox):[email protected]("refresh_fails", [False, True])+def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run, current_sandbox, refresh_fails):run_id = str(test_task_run.id)connection = {"sandbox_id": current_sandbox,@@ -128,8 +269,14 @@ def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run,"sandbox_jwt_kid": "fake-key","sandbox_backend": "modal",}- test_task_run.state = {"other": "preserved", **connection}+ accounting_state: dict[str, object] = {"unprocessed_request_ids": [], "token_cost": {}}+ test_task_run.state = {"other": "preserved", **connection, **accounting_state}test_task_run.save(update_fields=["state"])+ if refresh_fails:+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.refresh_task_run_cost",+ side_effect=OperationalError("unavailable"),+ )sandbox = mocker.Mock(id="sandbox-123")mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)publish_complete = mocker.patch(@@ -149,7 +296,9 @@ def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run,publish_complete.assert_called_once_with(run_id, False)test_task_run.refresh_from_db()assert test_task_run.state == (- {"other": "preserved"} if current_sandbox == "sandbox-123" else {"other": "preserved", **connection}+ {"other": "preserved", **accounting_state}+ | ({} if current_sandbox == "sandbox-123" else connection)+ | ({} if refresh_fails else {"compute_cost": None}))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 a311b2cd7172..c49ef943db25 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@@ -3,6 +3,8 @@ from datetime import timedeltaimport pytestfrom unittest.mock import MagicMock, patch+from django.db import OperationalError+from asgiref.sync import async_to_syncfrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironment@@ -656,28 +658,50 @@ class TestRecordRunTokenUsageMetrics:@pytest.mark.requires_secrets@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(- "origin_product,origin_key,wakes",+ "origin_product,origin_key,wakes,cost_failure,uses_gateway",[- (Task.OriginProduct.WORKFLOW, "job:step:1", True),- (Task.OriginProduct.USER_CREATED, None, False),+ (Task.OriginProduct.WORKFLOW, "job:step:1", True, False, True),+ (Task.OriginProduct.WORKFLOW, "job:step:1", True, True, True),+ (Task.OriginProduct.WORKFLOW, "job:step:1", True, False, False),+ (Task.OriginProduct.USER_CREATED, None, False, False, True),],)def test_terminal_transition_wakes_the_workflow_step_that_started_the_run(- activity_environment, test_task_run, origin_product, origin_key, wakes-):+ activity_environment: ActivityEnvironment,+ test_task_run: TaskRun,+ origin_product: str,+ origin_key: str | None,+ wakes: bool,+ cost_failure: bool,+ uses_gateway: bool,+) -> None:task = test_task_run.tasktask.origin_product = origin_producttask.origin_key = origin_keytask.save(update_fields=["origin_product", "origin_key"])test_task_run.output = {"final_message": "done"}- test_task_run.save(update_fields=["output"])+ test_task_run.state = (+ {"token_cost": {}, "unprocessed_request_ids": []} if uses_gateway else {"token_cost_incomplete": True}+ )+ test_task_run.save(update_fields=["output", "state"])input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.COMPLETED)- with patch("products.tasks.backend.logic.services.workflow_step_resume.emit_workflow_step_resume") as resume:- async_to_sync(activity_environment.run)(update_task_run_status, input_data)- async_to_sync(activity_environment.run)(update_task_run_status, input_data)+ with (+ patch("products.tasks.backend.logic.services.workflow_step_resume.emit_workflow_step_resume") as resume,+ patch("products.tasks.backend.models.posthoganalytics.capture") as capture,+ patch(+ "products.tasks.backend.logic.services.gateway_usage._compute_cost_source",+ side_effect=OperationalError("unavailable") if cost_failure else None,+ return_value=None,+ ),+ ):+ async_to_sync(_run_update_task_run_status)(activity_environment, input_data)+ async_to_sync(_run_update_task_run_status)(activity_environment, input_data)assert resume.call_count == (2 if wakes else 0)+ assert sum(call.kwargs.get("event") == "task_run_completed" for call in capture.call_args_list) == 1+ test_task_run.refresh_from_db()+ assert ("compute_cost" in test_task_run.state) is not cost_failureif wakes:assert resume.call_args.kwargs["origin_key"] == "job:step:1"assert resume.call_args.kwargs["status"] == "completed"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 d207483c7d00..c41930c2b260 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@@ -11,6 +11,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.error_telemetry import truncate_error_message+from products.tasks.backend.logic.services.gateway_usage import refresh_task_run_costfrom products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_runfrom products.tasks.backend.metrics import observe_prewarmed_unused_if_never_activated, observe_wizard_run_unboundfrom products.tasks.backend.models import Task, TaskRun@@ -120,6 +121,11 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:# Side effects run after commit, outside the row lock (repo convention: no side effects in atomic).if input.status in _TERMINAL_STATUSES:+ try:+ if task_run.environment == TaskRun.Environment.CLOUD:+ refresh_task_run_cost(run_id=task_run.id, team_id=task_run.team_id)+ except Exception:+ activity.logger.warning(f"Failed to refresh cost for run {task_run.id}", exc_info=True)resume_workflow_step_for_run(task_run)task_run.publish_stream_state_event()diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 3d699c7da897..663c720535cf 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -1,15 +1,21 @@+from __future__ import annotations+import jsonimport loggingfrom pathlib import Path+from typing import TYPE_CHECKINGimport pytestfrom unittest.mock import MagicMock, patch+from django.db import OperationalError+from posthog.models import Organization, Teamfrom products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGEfrom products.tasks.backend import model_catalogfrom products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS+from products.tasks.backend.facade.billing import get_task_run_costfrom products.tasks.backend.logic.services.sandbox_config import MAX_SANDBOX_TTL_SECONDSfrom products.tasks.backend.models import INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGINfrom products.tasks.backend.temporal.process_task import utils@@ -26,6 +32,11 @@ from products.tasks.backend.temporal.process_task.ai_gateway_token import ()from products.tasks.backend.temporal.process_task.utils import ai_gateway_env_vars+if TYPE_CHECKING:+ from pytest_django.fixtures import Settings++ from products.tasks.backend.models import TaskRun+class TestResolveSandboxAiProduct:"""Must agree with resolveAiProduct/resolveGatewayProduct in@@ -443,6 +454,7 @@ class TestProvisioningBoundaries:def _ctx(self):ctx = MagicMock()+ ctx.run_id = "00000000-0000-4000-8000-000000000007"ctx.team_id = 7ctx.origin_product = "signals_scout"ctx.state = {"ai_stage": "scout:logs"}@@ -450,7 +462,6 @@ class TestProvisioningBoundaries:ctx.sandbox_environment_id = Nonectx.model = "claude-sonnet-5"ctx.task_runtime = "acp"- ctx.run_id = "run-1"return ctxdef _task(self):@@ -458,10 +469,52 @@ class TestProvisioningBoundaries:task.internal = Truereturn task+ @pytest.mark.django_db+ @pytest.mark.parametrize(+ "task_runtime,tokens,initializes_cost,incomplete",+ [+ ("acp", ("phe_abc",), True, False),+ ("pi", ("phe_abc",), False, True),+ ("acp", (None,), False, True),+ ("acp", ("phe_abc", None, "phe_abc"), True, True),+ ("acp", (None, "phe_abc"), True, True),+ ("acp", (RuntimeError("routing failed"), "phe_abc"), True, True),+ ],+ )+ def test_gateway_cost_tracks_routing_across_provisioning_attempts(+ self,+ mint_settings: Settings,+ test_task_run: TaskRun,+ task_runtime: str,+ tokens: tuple[str | None | RuntimeError, ...],+ initializes_cost: bool,+ incomplete: bool,+ ) -> None:+ ctx = self._ctx()+ ctx.run_id = str(test_task_run.id)+ ctx.team_id = test_task_run.team_id+ ctx.task_runtime = task_runtime+ with patch.object(utils, "mint_scoped_token", side_effect=tokens):+ for token in tokens:+ env = utils.run_gateway_env_vars(ctx, self._task())+ assert env.get("AI_GATEWAY_TOKEN") == (+ token if isinstance(token, str) and task_runtime != "pi" else None+ )+ test_task_run.refresh_from_db()+ assert ("token_cost" in test_task_run.state) is initializes_cost+ assert ("unprocessed_request_ids" in test_task_run.state) is initializes_cost+ assert bool(test_task_run.state.get("token_cost_incomplete")) is incomplete+ assert get_task_run_cost(run_id=test_task_run.id, team_id=test_task_run.team_id).token_cost == (+ None if incomplete else 0+ )+def test_run_gateway_env_vars_maps_the_full_context(self, mint_settings):from products.tasks.backend.temporal.process_task import utils- with patch.object(utils, "ai_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"}) as env:+ with (+ patch.object(utils, "ai_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"}) as env,+ patch.object(utils, "record_gateway_routing"),+ ):out = utils.run_gateway_env_vars(self._ctx(), self._task())assert out == {"AI_GATEWAY_TOKEN": "phe"}env.assert_called_once_with(@@ -479,7 +532,10 @@ class TestProvisioningBoundaries:def test_non_slack_origin_skips_the_prior_run_lookup(self, mint_settings):from products.tasks.backend.temporal.process_task import utils- with patch("products.tasks.backend.models.TaskRun.objects") as runs:+ with (+ patch("products.tasks.backend.models.TaskRun.objects") as runs,+ patch.object(utils, "record_gateway_routing"),+ ):utils.run_gateway_env_vars(self._ctx(), self._task())runs.filter.assert_not_called()@@ -489,18 +545,29 @@ class TestProvisioningBoundaries:ctx = self._ctx()ctx.origin_product = "slack"ctx.state = {"run_source": "manual"}- with patch("products.tasks.backend.models.TaskRun.objects") as runs:+ with (+ patch("products.tasks.backend.models.TaskRun.objects") as runs,+ patch.object(utils, "record_gateway_routing"),+ ):runs.filter.return_value.exists.return_value = Truewith patch.object(utils, "ai_gateway_env_vars", return_value={}) as env:utils.run_gateway_env_vars(ctx, self._task())assert env.call_args.kwargs["prior_slack_run"] is True- def test_subscription_run_does_not_mint_gateway_credentials(self, mint_settings):+ @pytest.mark.django_db+ @pytest.mark.parametrize("access_field", ["claude_model_access", "codex_model_access"])+ def test_subscription_run_does_not_mint_gateway_credentials(+ self, mint_settings: Settings, test_task_run: TaskRun, access_field: str+ ) -> None:ctx = self._ctx()- ctx.claude_model_access = "own-subscription"+ ctx.run_id = str(test_task_run.id)+ ctx.team_id = test_task_run.team_id+ setattr(ctx, access_field, "own-subscription")with patch.object(utils, "mint_scoped_token") as mint:assert utils.run_gateway_env_vars(ctx, self._task()) == {}mint.assert_not_called()+ test_task_run.refresh_from_db()+ assert test_task_run.state["token_cost_incomplete"] is Truedef test_snapshot_builder_uses_the_shared_derivation(self, mint_settings):from products.tasks.backend.temporal.process_task import utils@@ -539,15 +606,19 @@ class TestProvisioningBoundaries:env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "slack_app"}with (patch.object(utils, "ai_gateway_env_vars", return_value=env),+ patch.object(utils, "record_gateway_routing"),patch("products.tasks.backend.models.TaskRun.update_state_atomic") as update,):utils.run_gateway_env_vars(self._ctx(), self._task())- update.assert_called_once_with("run-1", updates={"ai_gateway_product": "slack_app"})+ update.assert_called_once_with(+ "00000000-0000-4000-8000-000000000007", updates={"ai_gateway_product": "slack_app"}+ )def test_unpinned_mint_is_not_stamped(self, mint_settings):env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "signals_scout"}with (patch.object(utils, "ai_gateway_env_vars", return_value=env),+ patch.object(utils, "record_gateway_routing"),patch("products.tasks.backend.models.TaskRun.update_state_atomic") as update,):utils.run_gateway_env_vars(self._ctx(), self._task())@@ -558,15 +629,30 @@ class TestProvisioningBoundaries:ctx.state = {"ai_stage": "scout:logs", "ai_gateway_product": "slack_app"}with (patch.object(utils, "ai_gateway_env_vars", return_value={}),+ patch.object(utils, "record_gateway_routing"),patch("products.tasks.backend.models.TaskRun.update_state_atomic") as update,):utils.run_gateway_env_vars(ctx, self._task())- update.assert_called_once_with("run-1", remove_keys=["ai_gateway_product"])+ update.assert_called_once_with("00000000-0000-4000-8000-000000000007", remove_keys=["ai_gateway_product"])def test_routing_failure_leaves_the_run_on_the_python_gateway(self, mint_settings):- with patch.object(utils, "ai_gateway_env_vars", side_effect=RuntimeError("billing is down")):+ with (+ patch.object(utils, "ai_gateway_env_vars", side_effect=RuntimeError("billing is down")),+ patch.object(utils, "record_gateway_routing"),+ ):assert utils.run_gateway_env_vars(self._ctx(), self._task()) == {}+ @pytest.mark.parametrize("uses_gateway", [False, True])+ def test_routing_is_not_returned_when_accounting_write_fails(self, uses_gateway: bool) -> None:+ with (+ patch.object(+ utils, "ai_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"} if uses_gateway else {}+ ),+ patch.object(utils, "record_gateway_routing", side_effect=OperationalError("unavailable")),+ pytest.raises(OperationalError, match="unavailable"),+ ):+ utils.run_gateway_env_vars(self._ctx(), self._task())+def test_a_pinned_token_the_stamp_could_not_record_is_dropped(self, mint_settings):env = {"AI_GATEWAY_URL": "url",@@ -576,6 +662,7 @@ class TestProvisioningBoundaries:}with (patch.object(utils, "ai_gateway_env_vars", return_value=env),+ patch.object(utils, "record_gateway_routing"),patch("products.tasks.backend.models.TaskRun.update_state_atomic",side_effect=RuntimeError("postgres is down"),@@ -592,6 +679,7 @@ class TestProvisioningBoundaries:env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "signals_scout"}with (patch.object(utils, "ai_gateway_env_vars", return_value=env),+ patch.object(utils, "record_gateway_routing"),patch("products.tasks.backend.models.TaskRun.update_state_atomic",side_effect=RuntimeError("postgres is down"),diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.pyindex 965689ee5345..fa20bdbaa823 100644--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py@@ -1,4 +1,4 @@-from collections.abc import Callable+from collections.abc import Callable, Iteratorfrom typing import Any, castimport pytest@@ -33,6 +33,12 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox i_PROVISION = "products.tasks.backend.temporal.process_task.activities.provision_sandbox"[email protected](autouse=True)+def mock_gateway_accounting() -> Iterator[None]:+ with patch("products.tasks.backend.temporal.process_task.utils.record_gateway_routing"):+ yield++def _context(**overrides) -> TaskProcessingContext:defaults: dict[str, Any] = {"task_id": "task-123",diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 322aeee1eead..4ee3890adb8d 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -1366,6 +1366,10 @@ _CTX, _TASK = _gateway_ctx_task()return_value="https://us.posthog.com",)class TestBuildSandboxEnvironmentVariablesGateway(TestCase):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch("products.tasks.backend.temporal.process_task.utils.record_gateway_routing"))+def _build(self):ctx, task = _gateway_ctx_task()return build_sandbox_environment_variables(github_token=None, access_token="tok", ctx=ctx, task=task)@@ -1395,6 +1399,10 @@ class TestBuildSandboxEnvironmentVariablesGateway(TestCase):class TestBuildSandboxEnvironmentVariables(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch("products.tasks.backend.temporal.process_task.utils.record_gateway_routing"))+@patch("products.tasks.backend.logic.services.connection_token.get_sandbox_jwt_public_key",return_value="pub",diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex a20655ff995c..c698e5082f90 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -38,6 +38,7 @@ from products.tasks.backend.exceptions import CredentialUnavailableErrorfrom products.tasks.backend.feature_flags import is_mcp_exec_skills_enabledfrom products.tasks.backend.logic.model_access import ModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, PRODUCT_ALLOWED_MODELS+from products.tasks.backend.logic.services.gateway_usage import record_gateway_routingfrom products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.mcp_url import resolve_mcp_url as _resolve_mcp_url@@ -1363,6 +1364,7 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:TaskProcessingContext (duck-typed to avoid an import cycle); `task` the Task row."""if "own-subscription" in (ctx.claude_model_access, ctx.codex_model_access):+ record_gateway_routing(run_id=ctx.run_id, team_id=ctx.team_id, uses_gateway=False)return {}try:env_vars = ai_gateway_env_vars(@@ -1376,6 +1378,10 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:model=ctx.model,runtime=ctx.task_runtime,)+ if not _record_pinned_gateway_product(ctx.run_id, ctx.state, env_vars.get("AI_GATEWAY_PRODUCT")):+ # The model-change guard reads that stamp; unstamped, a run can move off its pin with no fallback.+ env_vars.pop("AI_GATEWAY_TOKEN", None)+ env_vars.pop("AI_GATEWAY_TOKEN_CAP_USD", None)except Exception:# Degrading to the Python gateway beats failing the provisioning activity and the run.AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()@@ -1384,11 +1390,13 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:extra={"run_id": ctx.run_id},exc_info=True,)- return {}- if not _record_pinned_gateway_product(ctx.run_id, ctx.state, env_vars.get("AI_GATEWAY_PRODUCT")):- # The model-change guard reads that stamp; unstamped, a run can move off its pin with no fallback.- env_vars.pop("AI_GATEWAY_TOKEN", None)- env_vars.pop("AI_GATEWAY_TOKEN_CAP_USD", None)+ env_vars = {}+ # Retry provisioning if coverage cannot be recorded; otherwise fallback usage can look fully accounted for.+ record_gateway_routing(+ run_id=ctx.run_id,+ team_id=ctx.team_id,+ uses_gateway=bool(env_vars.get("AI_GATEWAY_TOKEN")) and ctx.task_runtime != "pi",+ )return env_varsdiff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex b30d7a65897a..ef8c7c2d585c 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -265,7 +265,7 @@ class TestFacadeReadsAndMappers(TestCase):("a_human_reader_of_a_creatorless_task", False, False),])- def test_run_detail_serves_the_boot_prompt_to_the_sandbox_only(self, _name, include_agent_state, has_creator):+ def test_run_detail_filters_state_for_human_and_sandbox_readers(self, _name, include_agent_state, has_creator):# The agent reads initial_prompt_override off this payload to build its first# message; dropping it strips it silently and the run falls back to# task.description. But it embeds the triggering event wholesale (for a Slack@@ -285,6 +285,10 @@ class TestFacadeReadsAndMappers(TestCase):"systemPrompt": {"type": "preset", "preset": "claude_code", "append": "PostHog AI"},"sandbox_jwt_kid": "secret","task_summary": "Private workflow context",+ "token_cost": {"model": {"provider": {"cost_microusd": 4, "request_ids": ["request-1"]}}},+ "compute_cost": 2,+ "token_cost_incomplete": True,+ "unprocessed_request_ids": ["request-2"],"task_tags": ["private-tag"],},)@@ -301,6 +305,9 @@ class TestFacadeReadsAndMappers(TestCase):assert ("store_skills" in detail.state) is include_agent_stateassert ("systemPrompt" in detail.state) is include_agent_stateassert "sandbox_jwt_kid" not in detail.state+ assert {"token_cost", "compute_cost", "token_cost_incomplete", "unprocessed_request_ids"}.isdisjoint(+ detail.state+ )assert detail.task_summary == ("Private workflow context" if include_agent_state else None)assert detail.task_tags == (["private-tag"] if include_agent_state else [])diff --git a/products/tasks/backend/tests/test_gateway_usage.py b/products/tasks/backend/tests/test_gateway_usage.pynew file mode 100644index 000000000000..f213d750ce46--- /dev/null+++ b/products/tasks/backend/tests/test_gateway_usage.py@@ -0,0 +1,275 @@+from datetime import timedelta+from decimal import Decimal++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, Mock, patch++from django.test import override_settings+from django.utils import timezone++from asgiref.sync import sync_to_async+from parameterized import parameterized++from products.tasks.backend.facade.billing import TaskRunCost, get_task_cost, get_task_run_cost+from products.tasks.backend.logic.services.gateway_usage import (+ process_pending_gateway_usage,+ record_gateway_routing,+ record_generation_request,+ refresh_task_run_cost,+)+from products.tasks.backend.logic.services.sandbox_pricing import COMPUTE_RATE_CARDS+from products.tasks.backend.models import SandboxSession, Task, TaskRun+++@override_settings(SANDBOX_AI_GATEWAY_URL="https://gateway.example.com/v1", SANDBOX_AI_GATEWAY_MINT_KEY="phs_test")+class TestGatewayUsage(BaseTest):+ def _run(self, *, task: Task | None = None, status: str = TaskRun.Status.IN_PROGRESS) -> TaskRun:+ task = task or Task.objects.create(team=self.team, title="Cost test", description="")+ run = TaskRun.objects.create(team=self.team, task=task, status=status, environment=TaskRun.Environment.CLOUD)+ record_gateway_routing(run_id=run.id, team_id=self.team.id, uses_gateway=True)+ return run++ def _report(self, run: TaskRun, ids: list[str]) -> None:+ TaskRun.update_state_atomic(run.id, updates={"unprocessed_request_ids": ids})++ def _response(+ self, request_id: str, cost: object, *, model: str = "model-a", provider: str = "provider-a", status: int = 200+ ) -> MagicMock:+ response = MagicMock(+ status=status,+ json=AsyncMock(+ return_value={+ "request_id": request_id,+ "cost_usd": cost,+ "model": model,+ "provider": provider,+ }+ ),+ )+ response.__aenter__.return_value = response+ return response++ def _process(self, run: TaskRun, *, limit: int = 20) -> TaskRunCost:+ return process_pending_gateway_usage(run_id=run.id, team_id=self.team.id, limit=limit)++ @patch("aiohttp.ClientSession._request")+ def test_records_cost_by_model_and_provider_and_removes_processed_ids(self, get: Mock) -> None:+ run = self._run()+ self._report(run, ["parent", "subagent", "other-model", "second-turn", "parent"])+ get.side_effect = [+ self._response("parent", "0.005"),+ self._response("subagent", "0.010001", provider="provider-b"),+ self._response("other-model", "0.000009", model="model-b"),+ self._response("second-turn", "0.005"),+ ]+ assert self._process(run).token_cost == 2+ assert get.call_count == 4+ assert get.call_args.kwargs["timeout"].total == 15+ run.refresh_from_db()+ assert run.state == {+ "unprocessed_request_ids": [],+ "token_cost": {+ "model-a": {+ "provider-a": {"cost_microusd": 10_000, "request_ids": ["parent", "second-turn"]},+ "provider-b": {"cost_microusd": 10_001, "request_ids": ["subagent"]},+ },+ "model-b": {"provider-a": {"cost_microusd": 9, "request_ids": ["other-model"]}},+ },+ "compute_cost": None,+ }+ get.reset_mock()+ assert self._process(run).token_cost == 2+ get.assert_not_called()++ @patch("aiohttp.ClientSession._request")+ def test_overlapping_worker_pass_preserves_new_ids_and_adds_cost_once(self, get: Mock) -> None:+ run = self._run()+ self._report(run, ["request-1"])+ response = self._response("request-1", "0.015")++ async def other_worker(*_args: object, **_kwargs: object) -> MagicMock:+ get.side_effect = None+ get.return_value = response+ await sync_to_async(self._process)(run)+ await sync_to_async(self._report)(run, ["request-2"])+ return response++ get.side_effect = other_worker+ assert self._process(run).token_cost is None+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request-2"]+ assert run.state["token_cost"]["model-a"]["provider-a"] == {+ "cost_microusd": 15_000,+ "request_ids": ["request-1"],+ }++ @parameterized.expand([("unsettled",), ("connection_timeout",), ("body_timeout",)])+ @patch("aiohttp.ClientSession._request")+ def test_unavailable_cost_stays_queued_until_a_later_pass(self, failure: str, get: Mock) -> None:+ run = self._run(status=TaskRun.Status.CANCELLED)+ self._report(run, ["request-1"])+ get.return_value = self._response("request-1", "0", status=404)+ if failure == "connection_timeout":+ get.side_effect = TimeoutError+ elif failure == "body_timeout":+ get.return_value.status = 200+ get.return_value.json.side_effect = TimeoutError+ assert self._process(run).token_cost is None+ assert get_task_cost(team_id=self.team.id, task_id=run.task_id).token_cost is None+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request-1"]+ assert run.state["token_cost"] == {}+ get.side_effect = None+ get.return_value = self._response("request-1", "0.015")+ assert self._process(run).token_cost == 2+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == []++ @patch("aiohttp.ClientSession._request")+ def test_missing_responses_rotate_behind_other_pending_ids(self, get: Mock) -> None:+ run = self._run()+ self._report(run, ["missing", "priced"])+ get.return_value = self._response("missing", "0", status=404)+ self._process(run, limit=1)+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["priced", "missing"]+ get.return_value = self._response("priced", "0.10")+ assert self._process(run, limit=1).token_cost is None+ assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost is None+ assert get_task_cost(team_id=self.team.id, task_id=run.task_id).token_cost is None+ assert get.call_args.args[1].endswith("/v1/usage/priced")+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["missing"]++ @parameterized.expand([("0",), ("0.000001",)])+ @patch("aiohttp.ClientSession._request")+ def test_subcent_cost_is_processed_without_losing_precision(self, cost: str, get: Mock) -> None:+ run = self._run()+ self._report(run, ["request-1"])+ get.return_value = self._response("request-1", cost)+ assert self._process(run).token_cost == 0+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == []+ assert run.state["token_cost"]["model-a"]["provider-a"]["cost_microusd"] == int(Decimal(cost) * 1_000_000)++ @parameterized.expand([("negative", "-1"), ("nan", "NaN"), ("float", 0.5), ("exponent", "1e999999")])+ @patch("aiohttp.ClientSession._request")+ def test_invalid_gateway_cost_stays_queued(self, _name: str, cost: object, get: Mock) -> None:+ run = self._run()+ self._report(run, ["request-1"])+ get.return_value = self._response("request-1", cost)+ assert self._process(run).token_cost is None+ assert get_task_cost(team_id=self.team.id, task_id=run.task_id).token_cost is None+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request-1"]+ assert run.state["token_cost"] == {}++ @parameterized.expand([(True,), (False,)])+ @patch("aiohttp.ClientSession._request")+ def test_resume_preserves_pending_ids_and_processed_cost(self, fully_tracked: bool, get: Mock) -> None:+ run = self._run(status=TaskRun.Status.COMPLETED)+ self._report(run, ["old-request", "pending"])+ get.return_value = self._response("old-request", "0.015")+ self._process(run, limit=1)+ if not fully_tracked:+ record_gateway_routing(run_id=run.id, team_id=self.team.id, uses_gateway=False)+ record_gateway_routing(run_id=run.id, team_id=self.team.id, uses_gateway=True)+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["pending"]+ expected_cost = 2 if fully_tracked else None+ assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost is None+ assert get_task_cost(team_id=self.team.id, task_id=run.task_id).token_cost is None+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ self._report(run, ["old-request", "pending"])+ get.side_effect = [self._response("old-request", "0.015"), self._response("pending", "0.005")]+ assert self._process(run).token_cost == expected_cost+ run.refresh_from_db()+ assert run.state["token_cost"]["model-a"]["provider-a"]["request_ids"] == ["old-request", "pending"]+ assert run.state["token_cost"]["model-a"]["provider-a"]["cost_microusd"] == 20_000++ @patch("aiohttp.ClientSession._request")+ def test_getters_use_recorded_cost_and_round_across_runs(self, get: Mock) -> None:+ first = self._run(status=TaskRun.Status.FAILED)+ second = self._run(task=first.task, status=TaskRun.Status.CANCELLED)+ now = timezone.now()+ for index, run in enumerate((first, second)):+ SandboxSession.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=run,+ sandbox_id=f"sandbox-{index}",+ cpu_cores=2,+ memory_gb=4,+ ttl_seconds=600,+ created_at=now - timedelta(seconds=20),+ ttl_expires_at=now + timedelta(minutes=5),+ user_attributed_at=now - timedelta(seconds=20),+ ended_at=now,+ )+ request_id = f"request-{index}"+ self._report(run, [request_id])+ get.return_value = self._response(request_id, "0.005")+ self._process(run)+ get.reset_mock()+ assert get_task_run_cost(run_id=first.id, team_id=self.team.id) == TaskRunCost(token_cost=0, compute_cost=0)+ assert get_task_run_cost(run_id=second.id, team_id=self.team.id) == TaskRunCost(token_cost=0, compute_cost=0)+ with self.assertNumQueries(3):+ assert get_task_cost(team_id=self.team.id, task_id=first.task_id) == TaskRunCost(+ token_cost=1, compute_cost=1+ )+ get.assert_not_called()++ def test_untracked_runs_have_no_recorded_token_cost(self) -> None:+ run = self._run()+ assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost == 0+ run.state = {}+ run.save(update_fields=["state"])+ assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost is None++ def test_compute_cost_uses_existing_ledger_attribution_and_resource_floors(self) -> None:+ run = self._run()+ now = timezone.now()+ for name, attributed in (("prewarm", None), ("claimed", now - timedelta(hours=1))):+ SandboxSession.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=run,+ sandbox_id=name,+ cpu_cores=4,+ memory_gb=8,+ cpu_request_cores=1,+ memory_request_mb=1024,+ ttl_seconds=7200,+ created_at=now - timedelta(hours=2),+ ttl_expires_at=now + timedelta(hours=1),+ user_attributed_at=attributed,+ ended_at=now,+ )+ cost = get_task_run_cost(run_id=run.id, team_id=self.team.id)+ card = COMPUTE_RATE_CARDS[-1]+ expected = int(((card.cpu_core_second_usd + card.memory_gib_second_usd) * 3600 * 100).quantize(Decimal(1)))+ assert cost.compute_cost == expected+ assert get_task_cost(team_id=self.team.id, task_id=run.task_id) == cost+ run.refresh_from_db()+ assert "compute_cost" not in run.state+ assert refresh_task_run_cost(run_id=run.id, team_id=self.team.id) == cost+ run.refresh_from_db()+ assert run.state["compute_cost"] == expected+ assert set(run.state) == {"unprocessed_request_ids", "token_cost", "compute_cost"}++ @patch("aiohttp.ClientSession._request")+ def test_accounting_after_completion_has_no_completion_side_effects(self, get: Mock) -> None:+ run = self._run(status=TaskRun.Status.COMPLETED)+ Task.objects.filter(id=run.task_id).update(json_schema={"type": "object"})+ TaskRun.objects.filter(id=run.id).update(output={"result": "done"})+ run.refresh_from_db()+ completed_updated_at = run.updated_at+ get.return_value = self._response("late-request", "0.02")++ with patch.object(TaskRun, "track_structured_result") as track_result:+ record_gateway_routing(run_id=run.id, team_id=run.team_id, uses_gateway=True)+ record_generation_request(run_id=run.id, team_id=run.team_id, request_id="late-request")+ assert self._process(run).token_cost == 2+ assert get_task_run_cost(run_id=run.id, team_id=self.team.id).token_cost == 2+ track_result.assert_not_called()+ run.refresh_from_db()+ assert run.updated_at == completed_updated_atdiff --git a/products/tasks/backend/tests/test_gateway_usage_api.py b/products/tasks/backend/tests/test_gateway_usage_api.pynew file mode 100644index 000000000000..7a47a8c637e9--- /dev/null+++ b/products/tasks/backend/tests/test_gateway_usage_api.py@@ -0,0 +1,276 @@+import uuid+from decimal import Decimal++from posthog.test.base import APIBaseTest+from unittest.mock import Mock, patch++from django.db import OperationalError+from django.http import HttpResponse+from django.test import override_settings++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIClient++from posthog.models import ProjectSecretAPIKey, Team+from posthog.models.utils import hash_key_value++from products.tasks.backend.models import Task, TaskRun+++@override_settings(AI_GATEWAY_INTERNAL_TOKEN="gateway-token")+class TestTaskRunGatewayUsageAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.schedule_usage = self.enterContext(patch("products.tasks.backend.facade.gateway.schedule_gateway_usage"))++ def _run(+ self,+ *,+ team: Team | None = None,+ status_value: str = TaskRun.Status.IN_PROGRESS,+ environment: str = TaskRun.Environment.CLOUD,+ ) -> TaskRun:+ team = team or self.team+ task = Task.objects.create(+ team=team,+ created_by=self.user,+ title="Gateway usage task",+ description="Synthetic task",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ return TaskRun.objects.create(task=task, team=team, status=status_value, environment=environment)++ def _url(self, run: TaskRun, request_id: str = "request_1", *, team_id: int | None = None) -> str:+ return f"/internal/teams/{team_id or run.team_id}/task_runs/{run.id}/generation_requests/{request_id}/"++ def _post(+ self,+ run: TaskRun,+ request_id: str = "request_1",+ *,+ wallet_team_id: int | None = None,+ authorization: str = "Bearer gateway-token",+ data: object | None = None,+ ) -> HttpResponse:+ return APIClient().post(+ self._url(run, request_id),+ data,+ format="json",+ HTTP_AUTHORIZATION=authorization,+ HTTP_X_POSTHOG_GATEWAY_TEAM_ID=str(run.team_id if wallet_team_id is None else wallet_team_id),+ )++ def _mint_key_for(self, team: Team, token: str) -> None:+ ProjectSecretAPIKey.objects.create(+ team=team, label=f"mint-{uuid.uuid4().hex}", secure_value=hash_key_value(token)+ )++ @parameterized.expand([(TaskRun.Environment.CLOUD,), (TaskRun.Environment.LOCAL,)])+ def test_callback_accounts_only_cloud_runs_before_initialization(self, environment: str) -> None:+ run = self._run(environment=environment)+ updated_at = run.updated_at++ response = self._post(run)++ assert response.status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ if environment == TaskRun.Environment.CLOUD:+ assert run.state == {"unprocessed_request_ids": ["request_1"], "token_cost": {}}+ self.schedule_usage.assert_called_once()+ else:+ assert run.state == {}+ assert run.updated_at == updated_at+ self.schedule_usage.assert_not_called()++ def test_callback_rejects_missing_or_invalid_service_credential(self) -> None:+ run = self._run()++ for authorization in ("", "Bearer wrong", "Bearer caf\u00e9"):+ response = self._post(run, authorization=authorization)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ run.refresh_from_db()+ assert run.state == {}++ @override_settings(AI_GATEWAY_INTERNAL_TOKEN="")+ def test_callback_rejects_an_unconfigured_service_token(self) -> None:+ run = self._run()+ assert self._post(run).status_code == status.HTTP_401_UNAUTHORIZED++ @parameterized.expand([("state_write",), ("scheduling",)])+ def test_callback_does_not_acknowledge_a_failed_write_or_schedule(self, failure: str) -> None:+ run = self._run()+ client = APIClient()+ client.raise_request_exception = False+ target = (+ "products.tasks.backend.logic.services.gateway_usage._save_accounting_state"+ if failure == "state_write"+ else "products.tasks.backend.facade.gateway.schedule_gateway_usage"+ )+ with patch(target, side_effect=OperationalError("unavailable")):+ response = client.post(+ self._url(run),+ {},+ format="json",+ HTTP_AUTHORIZATION="Bearer gateway-token",+ HTTP_X_POSTHOG_GATEWAY_TEAM_ID=str(run.team_id),+ )+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ run.refresh_from_db()+ assert run.state == (+ {} if failure == "state_write" else {"unprocessed_request_ids": ["request_1"], "token_cost": {}}+ )+ assert self._post(run).status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request_1"]++ def test_callback_requires_a_valid_wallet_and_request_identifiers(self) -> None:+ run = self._run()++ assert self._post(run, wallet_team_id=0).status_code == status.HTTP_400_BAD_REQUEST+ assert self._post(run, request_id="not a request ID").status_code == status.HTTP_400_BAD_REQUEST+ assert (+ APIClient()+ .post(+ self._url(run),+ {},+ format="json",+ HTTP_AUTHORIZATION="Bearer gateway-token",+ )+ .status_code+ == status.HTTP_400_BAD_REQUEST+ )++ @override_settings(SANDBOX_AI_GATEWAY_MINT_KEY="phs_callback_mint")+ def test_callback_allows_the_configured_mint_key_wallet_for_another_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Gateway wallet")+ self._mint_key_for(other_team, "phs_callback_mint")+ run = self._run()++ response = self._post(run, wallet_team_id=other_team.id)++ assert response.status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request_1"]++ @override_settings(SANDBOX_AI_GATEWAY_MINT_KEY="phs_callback_mint")+ def test_callback_rejects_a_foreign_wallet(self) -> None:+ mint_team = Team.objects.create(organization=self.organization, name="Mint wallet")+ foreign_team = Team.objects.create(organization=self.organization, name="Foreign wallet")+ self._mint_key_for(mint_team, "phs_callback_mint")+ run = self._run()++ response = self._post(run, wallet_team_id=foreign_team.id)++ assert response.status_code == status.HTTP_403_FORBIDDEN+ run.refresh_from_db()+ assert run.state == {}++ def test_callback_is_idempotent_before_and_after_processing_and_terminalization(self) -> None:+ run = self._run()++ assert self._post(run).status_code == status.HTTP_204_NO_CONTENT+ assert self._post(run).status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request_1"]++ run.status = TaskRun.Status.COMPLETED+ run.state = {+ "unprocessed_request_ids": [],+ "token_cost": {"model": {"provider": {"cost_microusd": 4, "request_ids": ["request_1"]}}},+ }+ run.save(update_fields=["status", "state"])++ assert self._post(run).status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ assert run.status == TaskRun.Status.COMPLETED+ assert run.state["unprocessed_request_ids"] == []+ assert run.state["token_cost"]["model"]["provider"]["cost_microusd"] == 4+ assert self._post(run, "request_2").status_code == status.HTTP_204_NO_CONTENT+ run.refresh_from_db()+ assert run.state["unprocessed_request_ids"] == ["request_2"]+ assert run.status == TaskRun.Status.COMPLETED++ def test_callback_returns_not_found_for_a_run_outside_the_path_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ run = self._run(team=other_team)++ response = APIClient().post(+ self._url(run, team_id=self.team.id),+ {},+ format="json",+ HTTP_AUTHORIZATION="Bearer gateway-token",+ HTTP_X_POSTHOG_GATEWAY_TEAM_ID=str(self.team.id),+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_ordinary_patch_hides_and_protects_accounting_state(self) -> None:+ run = self._run()+ run.state = {+ "mode": "background",+ "unprocessed_request_ids": ["existing"],+ "token_cost": {"model": {"provider": {"cost_microusd": 4, "request_ids": ["existing"]}}},+ "token_cost_incomplete": True,+ "compute_cost": 2,+ }+ run.save(update_fields=["state"])++ response = self.client.patch(+ f"/api/projects/{self.team.id}/tasks/{run.task_id}/runs/{run.id}/",+ {+ "state": {+ "unprocessed_request_ids": ["forged"],+ "token_cost": {},+ "token_cost_incomplete": False,+ "compute_cost": 999,+ },+ "state_append": {"unprocessed_request_ids": "forged"},+ "state_remove_keys": [+ "unprocessed_request_ids",+ "token_cost",+ "token_cost_incomplete",+ "compute_cost",+ ],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["state"] == {"mode": "background"}+ run.refresh_from_db()+ assert run.state == {+ "mode": "background",+ "unprocessed_request_ids": ["existing"],+ "token_cost": {"model": {"provider": {"cost_microusd": 4, "request_ids": ["existing"]}}},+ "token_cost_incomplete": True,+ "compute_cost": 2,+ }++ @parameterized.expand([(False, True), (True, True), (False, False)])+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")+ @patch("products.tasks.backend.logic.services.gateway_usage._compute_cost_source", return_value=Decimal("0.12"))+ def test_terminal_patch_persists_cost_without_blocking_completion(+ self, refresh_fails: bool, uses_gateway: bool, compute_cost: Mock, signal: Mock+ ) -> None:+ run = self._run()+ run.state = {"unprocessed_request_ids": [], "token_cost": {}, "compute_cost": 7}+ if not uses_gateway:+ run.state = {"token_cost_incomplete": True, "compute_cost": 7}+ run.save(update_fields=["state"])+ if refresh_fails:+ compute_cost.side_effect = OperationalError("unavailable")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/tasks/{run.task_id}/runs/{run.id}/",+ {"status": TaskRun.Status.COMPLETED},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ run.refresh_from_db()+ assert response.json()["state"] == {}+ assert run.state["compute_cost"] == (7 if refresh_fails else 12)+ assert response.json()["updated_at"] == run.updated_at.isoformat().replace("+00:00", "Z")+ signal.assert_called_once_with(run.id, TaskRun.Status.COMPLETED, None)diff --git a/products/tasks/backend/tests/test_gateway_usage_workflow.py b/products/tasks/backend/tests/test_gateway_usage_workflow.pynew file mode 100644index 000000000000..5aa939b3ea6d--- /dev/null+++ b/products/tasks/backend/tests/test_gateway_usage_workflow.py@@ -0,0 +1,216 @@+import asyncio+import logging+from datetime import datetime, timedelta+from uuid import uuid4++import pytest+from unittest.mock import AsyncMock, Mock, patch++from django.test import override_settings++from asgiref.sync import sync_to_async+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.tasks.backend.logic.services.gateway_usage import (+ _gateway_usage_client,+ _schedule_gateway_usage,+ schedule_gateway_usage,+)+from products.tasks.backend.temporal.gateway_usage import GatewayUsageInput, TaskRunGatewayUsageWorkflow++[email protected]("failed_connection", [False, True])+async def test_scheduling_reuses_connection_after_success_and_retries_failure(failed_connection: bool) -> None:+ client = Mock(start_workflow=AsyncMock())+ _gateway_usage_client.cache_clear()+ with patch("posthog.temporal.common.client.async_connect", new_callable=AsyncMock) as connect:+ connect.side_effect = [RuntimeError("unavailable"), client] if failed_connection else None+ connect.return_value = client+ if failed_connection:+ with pytest.raises(RuntimeError, match="unavailable"):+ await _schedule_gateway_usage(run_id=uuid4(), team_id=7)+ await asyncio.gather(*(_schedule_gateway_usage(run_id=uuid4(), team_id=7) for _ in range(2)))+ await sync_to_async(schedule_gateway_usage)(run_id=uuid4(), team_id=7)+ assert connect.await_count == (2 if failed_connection else 1)+ assert client.start_workflow.await_count == 3+ _gateway_usage_client.cache_clear()+++def test_scheduling_reconnects_when_event_loop_changes() -> None:+ async def connect() -> Mock:+ loop = asyncio.get_running_loop()++ async def start(*args: object, **kwargs: object) -> None:+ assert asyncio.get_running_loop() is loop++ return Mock(start_workflow=AsyncMock(side_effect=start))++ with patch("posthog.temporal.common.client.async_connect", side_effect=connect) as connection:+ for _ in range(2):+ asyncio.run(_schedule_gateway_usage(run_id=uuid4(), team_id=7))+ assert connection.await_count == 2+ _gateway_usage_client.cache_clear()+++async def test_reconciliation_drains_retries_and_accepts_late_callbacks() -> None:+ run_id = uuid4()+ pending = list(range(23))+ attempts = 0+ signal_on_empty = True++ @activity.defn(name="reconcile_gateway_usage")+ async def reconcile(input: GatewayUsageInput) -> int:+ nonlocal attempts, signal_on_empty+ attempts += 1+ if attempts == 1:+ raise RuntimeError("temporary outage")+ del pending[:20]+ remaining = len(pending)+ if remaining == 0 and signal_on_empty:+ signal_on_empty = False+ pending.append(24)+ await _schedule_gateway_usage(run_id=run_id, team_id=7)+ return remaining++ async with (+ await WorkflowEnvironment.start_time_skipping() as env,+ Worker(+ env.client,+ task_queue="gateway-usage-test",+ workflows=[TaskRunGatewayUsageWorkflow],+ activities=[reconcile],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ),+ ):+ handles = []+ start_workflow = env.client.start_workflow++ async def capture_workflow(*args, **kwargs):+ handle = await start_workflow(*args, **kwargs)+ handles.append(handle)+ return handle++ with (+ patch.object(env.client, "start_workflow", side_effect=capture_workflow),+ override_settings(TASKS_TASK_QUEUE="gateway-usage-test"),+ patch(+ "posthog.temporal.common.client.async_connect",+ new=AsyncMock(return_value=env.client),+ ),+ ):+ await _schedule_gateway_usage(run_id=run_id, team_id=7)+ handle = handles[0]+ await asyncio.wait_for(handle.result(), timeout=30)+ assert pending == []+ assert attempts == 4++ pending.append(25)+ await _schedule_gateway_usage(run_id=run_id, team_id=7)+ await asyncio.wait_for(handles[-1].result(), timeout=30)+ assert pending == []+ assert attempts == 5+++async def test_reconciliation_drains_settled_backlog_without_backoff() -> None:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ pending = 100+ call_times: list[datetime] = []++ @activity.defn(name="reconcile_gateway_usage")+ async def reconcile(input: GatewayUsageInput) -> int:+ nonlocal pending+ call_times.append(await env.get_current_time())+ pending = max(pending - 20, 0)+ return pending++ async with Worker(+ env.client,+ task_queue="gateway-usage-test",+ workflows=[TaskRunGatewayUsageWorkflow],+ activities=[reconcile],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ run_id = uuid4()+ await env.client.execute_workflow(+ TaskRunGatewayUsageWorkflow.run,+ GatewayUsageInput(run_id=str(run_id), team_id=7),+ id=f"backlog-{run_id}",+ task_queue="gateway-usage-test",+ execution_timeout=timedelta(hours=1),+ )+ assert pending == 0+ assert len(call_times) == 5+ assert call_times[-1] - call_times[0] < timedelta(minutes=1)++[email protected]("activity_failure", [False, True])+async def test_reconciliation_expires_with_unresolved_usage(+ activity_failure: bool, caplog: pytest.LogCaptureFixture+) -> None:+ caplog.set_level(logging.WARNING, logger="temporalio.workflow")++ @activity.defn(name="reconcile_gateway_usage")+ async def reconcile(input: GatewayUsageInput) -> int:+ if activity_failure:+ raise RuntimeError("persistent outage")+ return 1++ async with (+ await WorkflowEnvironment.start_time_skipping() as env,+ Worker(+ env.client,+ task_queue="gateway-usage-test",+ workflows=[TaskRunGatewayUsageWorkflow],+ activities=[reconcile],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ),+ ):+ run_id = uuid4()+ await env.client.execute_workflow(+ TaskRunGatewayUsageWorkflow.run,+ GatewayUsageInput(+ run_id=str(run_id), team_id=7, retry_until=await env.get_current_time() + timedelta(minutes=1)+ ),+ id=f"exhausted-{run_id}",+ task_queue="gateway-usage-test",+ execution_timeout=timedelta(minutes=5),+ )+ assert "task_gateway_usage.retries_exhausted" in caplog.text+++async def test_callback_extends_deadline_during_activity_retries() -> None:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ run_id = uuid4()+ workflow_id = f"extended-{run_id}"+ original_deadline = await env.get_current_time() + timedelta(minutes=1)+ signaled = False+ settled = False++ @activity.defn(name="reconcile_gateway_usage")+ async def reconcile(input: GatewayUsageInput) -> int:+ nonlocal signaled, settled+ if not signaled:+ signaled = True+ await env.client.get_workflow_handle(workflow_id).signal(TaskRunGatewayUsageWorkflow.requests_available)+ if await env.get_current_time() < original_deadline:+ raise RuntimeError("outage until original deadline")+ settled = True+ return 0++ async with Worker(+ env.client,+ task_queue="gateway-usage-test",+ workflows=[TaskRunGatewayUsageWorkflow],+ activities=[reconcile],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ TaskRunGatewayUsageWorkflow.run,+ GatewayUsageInput(run_id=str(run_id), team_id=7, retry_until=original_deadline),+ id=workflow_id,+ task_queue="gateway-usage-test",+ execution_timeout=timedelta(minutes=5),+ )+ assert settleddiff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.pyindex dc3454aa1224..a1975a4130e8 100644--- a/products/tasks/backend/tests/test_workflow_dispatch.py+++ b/products/tasks/backend/tests/test_workflow_dispatch.py@@ -351,6 +351,46 @@ class TestWorkflowDispatchPersistence(TestCase):self.assertEqual(outcome, "already_active")+ @parameterized.expand([(False,), (True,)])+ def test_failed_restart_preserves_concurrent_state(self, use_dispatch: bool) -> None:+ run = self.task_run+ original_state = {"mode": "background", "sandbox_id": "old-sandbox", "pr_authorship_mode": "bot"}+ run.status = TaskRun.Status.COMPLETED+ run.environment = TaskRun.Environment.CLOUD+ run.state = original_state.copy()+ run.save(update_fields=["status", "environment", "state"])+ concurrent_state = {+ "unprocessed_request_ids": ["pending"],+ "token_cost": {"model": {"provider": {"request_ids": ["settled"], "cost_microusd": 10_000}}},+ "compute_cost": 3,+ "token_cost_incomplete": True,+ "task_summary": "Updated summary",+ }++ def fail_restart(*args: object) -> None:+ TaskRun.update_state_atomic(run.id, updates=concurrent_state)+ raise RuntimeError("unavailable")++ with (+ patch(+ "products.tasks.backend.feature_flags.is_workflow_dispatch_restart_enabled", return_value=use_dispatch+ ),+ patch("products.tasks.backend.facade.streams.reset_task_run_stream", return_value=True),+ patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow", side_effect=fail_restart),+ ):+ outcome, _, _ = resume_task_run_in_cloud(run.id, run.task_id, self.team.id, run.task.created_by_id)++ if use_dispatch:+ assert outcome == "resumed"+ dispatch = claim_dispatches("dispatcher-1", 1, timedelta(minutes=1))[0]+ TaskRun.update_state_atomic(run.id, updates=concurrent_state)+ assert mark_dead(dispatch.id, "dispatcher-1", "unavailable") == 1+ else:+ assert outcome == "workflow_failed"+ run.refresh_from_db()+ assert run.status == TaskRun.Status.COMPLETED+ assert run.state == {**original_state, **concurrent_state}+def test_reenqueuing_restart_resets_dispatch_age(self) -> None:snapshot = RestartSnapshot(status=TaskRun.Status.FAILED,