: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): enforce Desktop compute quota (#76923)
Adam Bowker6c242698b1dd
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex d8233fb03375..92eebf141ed0 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -91,6 +91,12 @@ TASKS_CONTINUE_AS_NEW_ENABLED: bool = get_from_env(type_cast=str_to_bool,)+TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED: bool = get_from_env(+ "TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED",+ False,+ type_cast=str_to_bool,+)+# Event-count threshold for the above; 0 relies on Temporal's is_continue_as_new_suggested().TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD: int = get_from_env("TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD", 4000, type_cast=intdiff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.pyindex 0b254b6b43b9..b24b1d1b3d3a 100644--- a/products/tasks/backend/exceptions.py+++ b/products/tasks/backend/exceptions.py@@ -5,6 +5,8 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exception+from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceeded+class ProcessTaskError(ApplicationError):def __init__(@@ -94,6 +96,19 @@ class SandboxProvisionError(ProcessTaskTransientError):pass+class ComputeBillingLimitError(ProcessTaskError, ComputeBillingLimitExceeded):+ def __init__(self, context: dict[str, Any]):+ from products.tasks.backend.logic.services.compute_quota import COMPUTE_QUOTA_DENIAL_CODE++ super().__init__(+ "Your organization reached its PostHog Desktop usage limit.",+ {**context, "reason": COMPUTE_QUOTA_DENIAL_CODE},+ None,+ capture=False,+ non_retryable=True,+ )++class SandboxNotFoundError(ProcessTaskFatalError):"""Sandbox does not exist."""diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.pyindex a6587ebc908d..7d334f647571 100644--- a/products/tasks/backend/facade/access.py+++ b/products/tasks/backend/facade/access.py@@ -10,6 +10,11 @@ Presentation imports it from here rather than reaching the internal ``access`` /"""from products.tasks.backend.access import has_loops_access, has_tasks_access-from products.tasks.backend.logic.services.code_usage_gate import usage_limit_response+from products.tasks.backend.logic.services.code_usage_gate import compute_quota_limit_response, usage_limit_response-__all__ = ["has_loops_access", "has_tasks_access", "usage_limit_response"]+__all__ = [+ "compute_quota_limit_response",+ "has_loops_access",+ "has_tasks_access",+ "usage_limit_response",+]diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex b4a0845335c8..6dc5b52f09ef 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3389,6 +3389,13 @@ def signal_task_run_user_message(run = _get_visible_run(run_id, task_id, team_id)if run is None:return None+ from products.tasks.backend.exceptions import (+ ComputeBillingLimitError, # noqa: PLC0415 — keep temporalio off the api import path+ )+ from products.tasks.backend.logic.services.compute_quota import is_compute_quota_exhausted # noqa: PLC0415++ if is_compute_quota_exhausted(run.task):+ raise ComputeBillingLimitError({"team_id": team_id, "task_id": str(task_id), "run_id": str(run_id)})try:context = {"actor_slack_user_id": actor_slack_user_id} if actor_slack_user_id else Nonesignal_task_followup_message(@@ -4470,6 +4477,11 @@ def create_task(if user_id is not None:validated_data["created_by"] = User.objects.get(id=user_id)+ if validated_data.get("repository") and not validated_data.get("github_integration"):+ default_integration = Integration.objects.filter(team=team, kind="github").first()+ if default_integration:+ validated_data["github_integration"] = default_integration+if (warm_branch_providedand validated_data["origin_product"] == Task.OriginProduct.USER_CREATED@@ -4510,6 +4522,18 @@ def create_task(warm_run = Noneif warm_run is not None:warm_task = warm_run.task+ should_set_client_provenance = warm_task.client_provenance is None and client_provenance is not None+ if should_set_client_provenance:+ warm_task.client_provenance = client_provenance+ from products.tasks.backend.exceptions import (+ ComputeBillingLimitError, # noqa: PLC0415 — keep temporalio off the api import path+ )+ from products.tasks.backend.logic.services.compute_quota import is_compute_quota_exhausted # noqa: PLC0415++ if is_compute_quota_exhausted(warm_task):+ raise ComputeBillingLimitError(+ {"team_id": team_id, "task_id": str(warm_task.id), "run_id": str(warm_run.id)}+ )description = (validated_data.get("description") or "").strip()update_fields: list[str] = []if description and not (warm_task.title or "").strip():@@ -4525,11 +4549,10 @@ def create_task(update_fields.append("channel")if update_fields:warm_task.save(update_fields=[*update_fields, "updated_at"])- if warm_task.client_provenance is None and client_provenance is not None:+ if should_set_client_provenance:Task.objects.filter(id=warm_task.id, client_provenance__isnull=True).update(client_provenance=client_provenance)- warm_task.client_provenance = client_provenance_activate_warm_run(warm_run,warm_task,diff --git a/products/tasks/backend/facade/compute_quota.py b/products/tasks/backend/facade/compute_quota.pynew file mode 100644index 000000000000..c056713b36b7--- /dev/null+++ b/products/tasks/backend/facade/compute_quota.py@@ -0,0 +1,2 @@+class ComputeBillingLimitExceeded(Exception):+ passdiff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.pyindex a1dab4574184..53f70691312d 100644--- a/products/tasks/backend/logic/services/code_usage_gate.py+++ b/products/tasks/backend/logic/services/code_usage_gate.py@@ -12,6 +12,7 @@ from posthog.models import OAuthAccessTokenfrom posthog.temporal.oauth import create_oauth_access_token_for_userfrom posthog.utils import get_instance_region+from products.tasks.backend.logic.services.compute_quota import COMPUTE_QUOTA_DENIAL_CODEfrom products.tasks.backend.metrics import observe_code_usage_gate_checkfrom products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer@@ -136,6 +137,19 @@ def rate_limit_error_payload(usage: CodeUsageStatus) -> dict[str, Any]:return payload+def compute_quota_limit_response() -> Response:+ return Response(+ TaskRunErrorResponseSerializer(+ {+ "type": "billing_limit",+ "code": COMPUTE_QUOTA_DENIAL_CODE,+ "error": "Your organization reached its PostHog Desktop usage limit.",+ }+ ).data,+ status=status.HTTP_429_TOO_MANY_REQUESTS,+ )++def usage_limit_response(user, team_id: int) -> Response | None:"""Return a 429 when the team is over its PostHog Desktop usage limit, else None.diff --git a/products/tasks/backend/logic/services/compute_quota.py b/products/tasks/backend/logic/services/compute_quota.pynew file mode 100644index 000000000000..c3074c828428--- /dev/null+++ b/products/tasks/backend/logic/services/compute_quota.py@@ -0,0 +1,64 @@+import logging++from django.conf import settings++from products.tasks.backend.metrics import observe_compute_quota_check+from products.tasks.backend.models import Task, TaskClientProvenance++COMPUTE_QUOTA_DENIAL_CODE = "posthog_code_billing_limit_exceeded"+logger = logging.getLogger(__name__)+++def is_task_billable_compute(task: Task) -> bool:+ source_loop = task.loop if task.loop_id is not None else None+ return is_billable_compute(+ origin_product=task.origin_product,+ client_provenance=task.client_provenance,+ source_loop_id=task.loop_id,+ source_loop_internal=source_loop.internal if source_loop is not None else None,+ )+++def is_billable_compute(+ *,+ origin_product: str | None,+ client_provenance: str | None,+ source_loop_id: object | None,+ source_loop_internal: bool | None,+) -> bool:+ if client_provenance != TaskClientProvenance.POSTHOG_DESKTOP:+ return False+ if origin_product == Task.OriginProduct.USER_CREATED:+ return True+ return bool(+ origin_product == Task.OriginProduct.LOOP and source_loop_id is not None and source_loop_internal is False+ )+++def is_compute_quota_exhausted(task: Task) -> bool:+ if not getattr(settings, "TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED", False):+ return False+ if not is_task_billable_compute(task):+ return False+ try:+ exhausted = _is_posthog_code_quota_limited(task.team.api_token)+ except Exception:+ observe_compute_quota_check("fail_open")+ logger.warning(+ "compute_quota: PostHog Code quota state unavailable",+ extra={"team_id": task.team_id, "task_id": str(task.id)},+ exc_info=True,+ )+ return False+ observe_compute_quota_check("checked_blocked" if exhausted else "checked_allowed")+ return exhausted+++def _is_posthog_code_quota_limited(team_api_token: str) -> bool:+ from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited++ return is_team_limited(+ team_api_token,+ QuotaResource.POSTHOG_CODE_CREDITS,+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,+ )diff --git a/products/tasks/backend/logic/services/sandbox_usage.py b/products/tasks/backend/logic/services/sandbox_usage.pyindex 99fe8f9e5b93..c70330e1c1ef 100644--- a/products/tasks/backend/logic/services/sandbox_usage.py+++ b/products/tasks/backend/logic/services/sandbox_usage.py@@ -25,6 +25,7 @@ from django.utils import timezoneimport structlog+from products.tasks.backend.logic.services.compute_quota import is_billable_computefrom products.tasks.backend.logic.services.sandbox import Sandbox, SandboxBase, SandboxConfigfrom products.tasks.backend.logic.services.sandbox_pricing import (COMPUTE_RATE_CARDS,@@ -246,25 +247,28 @@ def get_billable_sandbox_compute_usage_by_team(cards = validate_compute_rate_cards(rate_cards)sessions = (SandboxSession.objects.unscoped()+ .select_related("task_run__task__loop").filter(client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,user_attributed_at__isnull=False,user_attributed_at__lt=end,)- .filter(- Q(origin_product=Task.OriginProduct.USER_CREATED)- | Q(- origin_product=Task.OriginProduct.LOOP,- task_run__task__loop__isnull=False,- task_run__task__loop__internal=False,- )- )+ .filter(Q(origin_product=Task.OriginProduct.USER_CREATED) | Q(origin_product=Task.OriginProduct.LOOP)).filter(Q(ended_at__isnull=True, ttl_expires_at__gt=begin) | Q(ended_at__gt=begin)))usage: dict[int, list[Decimal]] = {}calculated_at = timezone.now()for session in sessions.iterator():+ task = session.task_run.task+ source_loop = task.loop if task.loop_id is not None else None+ if not is_billable_compute(+ origin_product=session.origin_product,+ client_provenance=session.client_provenance,+ source_loop_id=task.loop_id,+ source_loop_internal=source_loop.internal if source_loop is not None else None,+ ):+ continuecost = calculate_sandbox_compute_cost(session, begin, end, calculated_at=calculated_at, rate_cards=cards)totals = usage.setdefault(session.team_id, [Decimal(0) for _ in range(3)])totals[0] += cost.cpu_core_secondsdiff --git a/products/tasks/backend/logic/services/tests/test_compute_quota.py b/products/tasks/backend/logic/services/tests/test_compute_quota.pynew file mode 100644index 000000000000..1d9d05fb4533--- /dev/null+++ b/products/tasks/backend/logic/services/tests/test_compute_quota.py@@ -0,0 +1,84 @@+import pytest+from unittest.mock import patch++from django.test import override_settings++from posthog.models import Organization, Team++from products.tasks.backend.logic.services.compute_quota import (+ is_billable_compute,+ is_compute_quota_exhausted,+ is_task_billable_compute,+)+from products.tasks.backend.models import Loop, Task, TaskClientProvenance+++class TestComputeQuota:+ @pytest.fixture(autouse=True)+ def setup(self):+ organization = Organization.objects.create(name="test")+ self.team = Team.objects.create(organization=organization, name="test")++ def task(self, **overrides):+ defaults = {+ "team": self.team,+ "title": "task",+ "description": "task",+ "origin_product": Task.OriginProduct.USER_CREATED,+ "client_provenance": TaskClientProvenance.POSTHOG_DESKTOP,+ }+ defaults.update(overrides)+ return Task.objects.create(**defaults)++ @override_settings(TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED=False)+ @patch("products.tasks.backend.logic.services.compute_quota._is_posthog_code_quota_limited", return_value=True)+ def test_inactive_enforcement_never_blocks(self, limited):+ assert not is_compute_quota_exhausted(self.task())+ limited.assert_not_called()++ @override_settings(TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED=True)+ @patch("products.tasks.backend.logic.services.compute_quota._is_posthog_code_quota_limited")+ def test_combined_posthog_code_quota_controls_billable_task(self, limited):+ task = self.task()+ limited.side_effect = [True, False]++ assert is_compute_quota_exhausted(task)+ assert not is_compute_quota_exhausted(task)+ limited.assert_called_with(self.team.api_token)++ @override_settings(TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED=True)+ @patch(+ "products.tasks.backend.logic.services.compute_quota._is_posthog_code_quota_limited",+ side_effect=ConnectionError,+ )+ def test_unavailable_quota_state_fails_open(self, _limited):+ assert not is_compute_quota_exhausted(self.task())++ @pytest.mark.parametrize(+ "origin,provenance",+ [+ (Task.OriginProduct.SLACK, TaskClientProvenance.POSTHOG_DESKTOP),+ (Task.OriginProduct.SIGNAL_REPORT, TaskClientProvenance.POSTHOG_DESKTOP),+ (Task.OriginProduct.USER_CREATED, None),+ ],+ )+ def test_non_billable_origins_are_ineligible(self, origin, provenance):+ assert not is_task_billable_compute(self.task(origin_product=origin, client_provenance=provenance))++ def test_unknown_origin_is_ineligible(self):+ assert not is_billable_compute(+ origin_product=None,+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,+ source_loop_id=None,+ source_loop_internal=None,+ )++ def test_only_direct_non_internal_desktop_loop_is_eligible(self):+ loop_defaults = {"team": self.team, "instructions": "run", "runtime_adapter": "agent"}+ user_loop = Loop.objects.unscoped().create(**loop_defaults, name="user", internal=False)+ internal_loop = Loop.objects.unscoped().create(**loop_defaults, name="internal", internal=True)++ assert is_task_billable_compute(self.task(origin_product=Task.OriginProduct.LOOP, loop=user_loop))+ assert not is_task_billable_compute(self.task(origin_product=Task.OriginProduct.LOOP, loop=internal_loop))+ assert not is_task_billable_compute(self.task(origin_product=Task.OriginProduct.LOOP))diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 8be09230b923..ab3b92c6c4ee 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -222,6 +222,7 @@ LOOP_AUTO_PAUSED_TOTAL = Counter()CodeUsageGateOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"]+ComputeQuotaOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"]# outcome: checked_allowed/checked_blocked when the LLM gateway answered the usage check,# fail_open when a gateway/token error let the run proceed unchecked (see LOOPS.md Security:@@ -232,6 +233,16 @@ CODE_USAGE_GATE_CHECK_TOTAL = Counter(labelnames=["outcome"],)+COMPUTE_QUOTA_CHECK_TOTAL = Counter(+ "posthog_tasks_compute_quota_check_total",+ "Compute quota-check outcomes for billable PostHog Desktop runs",+ labelnames=["outcome"],+)+++def observe_compute_quota_check(outcome: ComputeQuotaOutcome) -> None:+ COMPUTE_QUOTA_CHECK_TOTAL.labels(outcome=outcome).inc()+def _metric_label(value: object | None) -> str:if value is None:diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 26afc5fe4ae6..5a5a54a31107 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -58,8 +58,9 @@ from products.tasks.backend.facade import (cancellation as tasks_cancellation,contracts as tasks_contracts,)-from products.tasks.backend.facade.access import usage_limit_response+from products.tasks.backend.facade.access import compute_quota_limit_response, usage_limit_responsefrom products.tasks.backend.facade.client_provenance import get_task_client_provenance+from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceededfrom products.tasks.backend.facade.metrics import (StreamConnectionOutcome,observe_stream_connection_closed,@@ -430,17 +431,29 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):data = TaskCommentDetailSerializer(comment).datareturn Response(data)- @extend_schema(request=TaskCreateSerializer, responses={201: TaskSerializer})+ @extend_schema(+ request=TaskCreateSerializer,+ responses={+ 201: TaskSerializer,+ 429: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="Organization reached its PostHog Desktop usage limit",+ ),+ },+ )def create(self, request, **kwargs):serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)# Read before create_task, which pops the relationship out of the dict it's handed.relationship = serializer.validated_data.get("signal_report_task_relationship")- task = tasks_facade.create_task(- self.team_id,- self._user_id(),- validated_data=dict(serializer.validated_data),- client_provenance=get_task_client_provenance(request),- )+ try:+ task = tasks_facade.create_task(+ self.team_id,+ self._user_id(),+ validated_data=dict(serializer.validated_data),+ client_provenance=get_task_client_provenance(request),+ )+ except ComputeBillingLimitExceeded:+ return compute_quota_limit_response()self._forward_signals_discussion_note(request, task, relationship)return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)@@ -1927,6 +1940,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):description="Invalid command or no active sandbox",),404: OpenApiResponse(description="Task run not found"),+ 429: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="Organization reached its PostHog Desktop usage limit",+ ),502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),},summary="Send command to task run",@@ -1998,6 +2015,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):message_id=str(request_id) if request_id is not None else None,steer=command_params.get("steer", False),)+ except ComputeBillingLimitExceeded:+ return compute_quota_limit_response()except Exception:# A synchronous web request can't retry the way the Temporal# follow-up path does, so a transient signalling failure surfacesdiff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 90d350ed3769..1fd41aaf2ea8 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -17,6 +17,8 @@ from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticfrom posthog.permissions import APIScopePermissionfrom products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.access import compute_quota_limit_response+from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceededfrom products.tasks.backend.presentation.serializers import (ChannelContextGenerationSerializer,ChannelFeedMessageSerializer,@@ -34,6 +36,7 @@ from products.tasks.backend.presentation.serializers import (TaskActivitySerializer,TaskMentionQuerySerializer,TaskMentionSerializer,+ TaskRunErrorResponseSerializer,TaskThreadMessageSerializer,TaskThreadMessageWriteSerializer,)@@ -551,13 +554,20 @@ class TaskThreadMessageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: TaskThreadMessageSerializer,400: OpenApiResponse(description="No signalable run, or message already forwarded"),+ 429: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="Organization reached its PostHog Desktop usage limit",+ ),},summary="Send a thread message to the agent",description="Task author only: forwards the message into the task's latest live run.",)@action(detail=True, methods=["post"], url_path="send_to_agent", required_scopes=["task:write"])def send_to_agent(self, request, pk=None, **kwargs):- kind, message = tasks_facade.forward_thread_message(pk, self._task_id(), self.team_id, self._user_id())+ try:+ kind, message = tasks_facade.forward_thread_message(pk, self._task_id(), self.team_id, self._user_id())+ except ComputeBillingLimitExceeded:+ return compute_quota_limit_response()if kind == "not_found":raise NotFound()if kind == "forbidden":diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.pyindex b83a5e39eaf6..5595e9b0c289 100644--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py@@ -66,7 +66,7 @@ def forward_pending_user_message(run_id: str) -> None:from products.tasks.backend.models import TaskRuntry:- task_run = TaskRun.objects.select_related("task__created_by", "task__team").get(id=run_id)+ task_run = TaskRun.objects.select_related("task__created_by", "task__team", "task__loop").get(id=run_id)except TaskRun.DoesNotExist:# The run existed when this workflow started, so a missing row means it was# hard-deleted mid-run (team/org deletion cascade). Fail the workflow rather@@ -104,6 +104,15 @@ def forward_pending_user_message(run_id: str) -> None:if not pending_message and not pending_user_artifact_ids:return+ if state.get("await_user_message"):+ from products.tasks.backend.exceptions import ComputeBillingLimitError+ from products.tasks.backend.logic.services.compute_quota import is_compute_quota_exhausted++ if is_compute_quota_exhausted(task_run.task):+ raise ComputeBillingLimitError(+ {"team_id": task_run.team_id, "task_id": str(task_run.task_id), "run_id": run_id}+ )+pending_message_id = state.get("pending_user_message_id")assert isinstance(pending_message_id, str) and pending_message_iddiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 98ed3cb92a89..c1ce9d8d9169 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -17,12 +17,14 @@ from products.tasks.backend.constants import (filter_user_sandbox_env_vars,)from products.tasks.backend.exceptions import (+ ComputeBillingLimitError,CredentialUnavailableError,GitHubAuthenticationError,OAuthTokenError,TaskNotFoundError,)from products.tasks.backend.logic.services.agentsh import _get_debug_only_domains, enforced_egress_domains+from products.tasks.backend.logic.services.compute_quota import is_compute_quota_exhaustedfrom products.tasks.backend.logic.services.connection_token import (SANDBOX_JWT_STATE_KID_KEY,get_primary_sandbox_jwt_kid,@@ -255,9 +257,9 @@ def _resolve_sandbox_github_token(def _load_task(ctx: TaskProcessingContext) -> Task:try:- return Task.objects.select_related("created_by", "github_integration", "github_user_integration").get(- id=ctx.task_id- )+ return Task.objects.select_related(+ "created_by", "github_integration", "github_user_integration", "team", "loop"+ ).get(id=ctx.task_id)except Task.DoesNotExist as e:raise TaskNotFoundError(f"Task {ctx.task_id} not found", {"task_id": ctx.task_id}, cause=e)@@ -566,6 +568,10 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Creimage_source=prepared.image_source,**ctx.to_log_context(),):+ if settings.TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED and not (ctx.state or {}).get("await_user_message"):+ task = _load_task(ctx)+ if is_compute_quota_exhausted(task):+ raise ComputeBillingLimitError({"team_id": ctx.team_id, "task_id": ctx.task_id, "run_id": ctx.run_id})_emit_image_source_log(ctx, prepared)emit_agent_log(ctx.run_id,diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex f337bb495a91..f7cbce16db5f 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -11,6 +11,7 @@ from rest_framework.test import APIClientfrom posthog.models import Integration, Organization, OrganizationMembership, Team, User+from products.tasks.backend.exceptions import ComputeBillingLimitErrorfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.models import Channel, ChannelFeedMessage, Task, TaskActivity, TaskRun, TaskThreadMessagefrom products.tasks.backend.push_dispatcher import (@@ -311,6 +312,20 @@ class ThreadMessagesAPITestCase(ChannelTaskAPITestCase):again = self.author_client.post(f"{self._thread_url()}{message_id}/send_to_agent/")self.assertEqual(again.status_code, status.HTTP_400_BAD_REQUEST)+ def test_send_to_agent_returns_structured_compute_quota_denial(self):+ TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ message_id = self.peer_client.post(self._thread_url(), {"content": "try X"}).json()["id"]++ with patch(+ "products.tasks.backend.facade.api.signal_task_run_user_message",+ side_effect=ComputeBillingLimitError({"team_id": self.team.id}),+ ):+ response = self.author_client.post(f"{self._thread_url()}{message_id}/send_to_agent/")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "posthog_code_billing_limit_exceeded")+ self.assertIsNone(TaskThreadMessage.objects.unscoped().get(id=message_id).forwarded_to_agent_at)+def test_thread_hidden_when_task_not_visible(self):private_task = Task.objects.create(team=self.team,diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex 1474a56e048c..87dfde72faf8 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -5,6 +5,7 @@ from unittest.mock import patchfrom django.utils import timezone as django_timezone+from rest_framework import statusfrom rest_framework.exceptions import PermissionDenied, Throttledfrom posthog.exceptions import QuotaLimitExceeded@@ -424,6 +425,23 @@ class TestCreateTaskWarmReuse(APIBaseTest):run.refresh_from_db()assert "await_user_message" not in run.state+ def test_create_endpoint_returns_structured_compute_quota_denial_before_warm_activation(self):+ warm_task, run = self._warm_run()++ with patch("products.tasks.backend.logic.services.compute_quota.is_compute_quota_exhausted", return_value=True):+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {"description": "fix the bug", "repository": "posthog/posthog", "branch": "main"},+ format="json",+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert response.json()["code"] == "posthog_code_billing_limit_exceeded"+ warm_task.refresh_from_db()+ run.refresh_from_db()+ assert warm_task.description == ""+ assert run.state.get("await_user_message") is True+def test_does_not_overwrite_existing_warm_description(self):warm_task, _ = self._warm_run()warm_task.description = "already there"