Skip to content

: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.

fix(billing): block deactivated orgs from cloud tasks and AI spend (#83003)

Charles Vienbfca34a9d2a8
diff --git a/ee/api/quota_limits.py b/ee/api/quota_limits.py
index 107a78c0056f..b62ad2ccd874 100644
--- a/ee/api/quota_limits.py
+++ b/ee/api/quota_limits.py
@@ -25,7 +25,11 @@ from ee.billing.quota_limiting import INFORMATIONAL_USAGE_RESOURCES, QuotaResour
class QuotaResourceLimitSerializer(serializers.Serializer):
limited = serializers.BooleanField(
- help_text="True when the team is currently over its quota for this resource and limits are in effect.",
+ help_text=(
+ "True when the team is currently over its quota for this resource and limits are in "
+ "effect. A deactivated organization additionally reads as limited on the two credit "
+ "buckets `ai_credits` and `posthog_code_credits`, regardless of usage."
+ ),
)
usage = serializers.FloatField(
allow_null=True,
@@ -74,7 +78,8 @@ class QuotaLimitsResponseSerializer(serializers.Serializer):
"Whether the team's organization pays for PostHog Desktop usage: billing grants the "
"`posthog_code_usage` product feature only on the Desktop usage product's paid plan, "
"synced into the organization's available features. Consumers gate paid-tier Desktop "
- "behavior on this; an org unknown to billing reads as not paying."
+ "behavior on this; an org unknown to billing reads as not paying. Always false for "
+ "deactivated organizations."
),
)
@@ -98,9 +103,18 @@ class QuotaLimitsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
org_usage = self.team.organization.usage or {}
+ org_deactivated = self.team.organization.is_active is False
# Fresh read on purpose: the gateway re-caches this answer for minutes, so serving
# the 30s per-worker memo here would re-poison a just-invalidated gateway entry.
- limited_resources = get_fresh_team_limited_resources(self.team.api_token)
+ # A deactivated org (for any reason) instead reads as limited on just the two credit
+ # buckets the gateway enforces on — that blocks AI and Desktop spend without dropping
+ # events, recordings, or syncs, and without depending on Redis being reachable.
+ if org_deactivated:
+ limited_resources = dict.fromkeys(QuotaResource, False)
+ limited_resources[QuotaResource.AI_CREDITS] = True
+ limited_resources[QuotaResource.POSTHOG_CODE_CREDITS] = True
+ else:
+ limited_resources = get_fresh_team_limited_resources(self.team.api_token)
limited = {}
for resource in QuotaResource:
summary = org_usage.get(resource.value) or {}
@@ -118,9 +132,8 @@ class QuotaLimitsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
data = QuotaLimitsResponseSerializer(
{
"limited": limited,
- "code_usage_billing_active": self.team.organization.is_feature_available(
- AvailableFeature.POSTHOG_CODE_USAGE
- ),
+ "code_usage_billing_active": not org_deactivated
+ and self.team.organization.is_feature_available(AvailableFeature.POSTHOG_CODE_USAGE),
}
).data
return Response(data)
diff --git a/ee/api/test/test_quota_limits.py b/ee/api/test/test_quota_limits.py
index f71f0dcc3cfa..0ed5e4232067 100644
--- a/ee/api/test/test_quota_limits.py
+++ b/ee/api/test/test_quota_limits.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from rest_framework import status
@@ -58,6 +59,43 @@ class TestQuotaLimitsAPI(APIBaseTest):
# Org holds no billing-granted Desktop usage feature -> reads as not paying
self.assertIs(data["code_usage_billing_active"], False)
+ def test_any_deactivated_org_limits_only_credit_buckets_and_reads_unbilled(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.POSTHOG_CODE_USAGE, "name": "PostHog Desktop usage billing"}
+ ]
+ self.organization.is_active = False
+ self.organization.is_not_active_reason = "Past due invoice"
+ self.organization.save()
+
+ # The deactivated-org answer must not depend on Redis being reachable.
+ with patch(
+ "ee.api.quota_limits.get_fresh_team_limited_resources",
+ side_effect=Exception("redis unavailable"),
+ ):
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ credit_buckets = {QuotaResource.AI_CREDITS.value, QuotaResource.POSTHOG_CODE_CREDITS.value}
+ for resource in QuotaResource:
+ expected = resource.value in credit_buckets
+ self.assertIs(data["limited"][resource.value]["limited"], expected)
+ for field in INFORMATIONAL_USAGE_RESOURCES:
+ self.assertIs(data["limited"][field]["limited"], False)
+ self.assertIs(data["code_usage_billing_active"], False)
+
+ def test_null_active_org_is_not_treated_as_deactivated(self) -> None:
+ self.organization.is_active = None
+ self.organization.save()
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["limited"]["ai_credits"],
+ {"limited": False, "usage": None, "limit": None},
+ )
+
def test_reports_code_usage_billing_state(self) -> None:
# The LLM gateway keys posthog_code per-user cap bypass and model gating
# on this field - dropping it (or resolving the wrong org) silently
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index 1a79482eefd4..f3f9975d21e8 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -664,18 +664,15 @@ def invalidate_llm_gateway_quota_cache(team_ids: Iterable[int]) -> None:
Best-effort by design: the gateway TTL already bounds staleness, so a failure
here must not fail the billing update that just committed.
"""
- cache_keys = [
- key
- for team_id in team_ids
- for key in (
- f"quota:code_usage_billing:team:{team_id}",
- *(f"quota:{resource.value}:team:{team_id}" for resource in QuotaResource),
- )
- ]
- if not cache_keys:
+ id_set = {int(team_id) for team_id in team_ids}
+ if not id_set:
return
try:
- get_client(settings.LLM_GATEWAY_REDIS_URL).delete(*cache_keys)
+ pipeline = get_client(settings.LLM_GATEWAY_REDIS_URL).pipeline(transaction=False)
+ for team_id in id_set:
+ pipeline.incr(f"quota:generation:team:{team_id}")
+ pipeline.delete(f"quota:code_usage_billing:team:{team_id}")
+ pipeline.execute()
except Exception as e:
capture_exception(e)
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 4116060a2da2..0c23ad57dab7 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -980,17 +980,18 @@ class TestQuotaLimiting(BaseTest):
def test_update_org_billing_quotas_invalidates_llm_gateway_quota_cache(self) -> None:
gateway_redis_url = "redis://llm-gateway-redis-test/"
- cache_keys = [
- f"quota:posthog_code_credits:team:{self.team.id}",
- f"quota:ai_credits:team:{self.team.id}",
- f"quota:code_usage_billing:team:{self.team.id}",
- ]
+ # Per-resource entries carry the gateway's credential-fingerprint suffix; the
+ # billing bit is keyed per team (see _redis_key/_billing_key in quota_resolver).
+ billing_key = f"quota:code_usage_billing:team:{self.team.id}"
+ generation_key = f"quota:generation:team:{self.team.id}"
+ other_generation_key = f"quota:generation:team:{self.team.id + 1}"
with self.settings(LLM_GATEWAY_REDIS_URL=gateway_redis_url):
gateway_redis = get_client(gateway_redis_url)
- gateway_redis.mset(dict.fromkeys(cache_keys, "stale"))
+ gateway_redis.set(billing_key, "stale")
+ gateway_redis.set(other_generation_key, 4)
# Seed the central Redis too: eviction must target the gateway's own
# instance, not the default client (which would silently no-op in prod).
- self.redis_client.mset(dict.fromkeys(cache_keys, "central"))
+ self.redis_client.set(billing_key, "central")
self.organization.usage = {
"events": {"usage": 1, "limit": 100},
"period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
@@ -998,9 +999,11 @@ class TestQuotaLimiting(BaseTest):
update_org_billing_quotas(self.organization)
- assert gateway_redis.mget(cache_keys) == [None] * len(cache_keys)
- assert self.redis_client.mget(cache_keys) == [b"central"] * len(cache_keys)
- self.redis_client.delete(*cache_keys)
+ assert gateway_redis.get(billing_key) is None
+ assert gateway_redis.get(generation_key) == b"1"
+ assert gateway_redis.get(other_generation_key) == b"4"
+ assert self.redis_client.get(billing_key) == b"central"
+ self.redis_client.delete(billing_key)
def test_update_org_billing_quotas(self):
with freeze_time("2021-01-01T12:59:59Z"):
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 0630b9443e82..d02988dcd635 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -196,6 +196,13 @@ class OrganizationAdmin(admin.ModelAdmin):
# this page without core importing it. See posthog.admin.inline_registry.
return [*super().get_inlines(request, obj), *extra_inlines_for(Organization)]
+ def changeform_view(self, request, object_id=None, form_url="", extra_context=None):
+ extra_context = {
+ **(extra_context or {}),
+ "deactivation_reason_presets": list(Organization.DeactivationReason.values),
+ }
+ return super().changeform_view(request, object_id, form_url, extra_context)
+
def members_count(self, organization: Organization):
return organization.members.count()
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 91d9c3afc5eb..a1298c4750f8 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -185,6 +185,18 @@ class Organization(ModelActivityMixin, UUIDTModel):
BAYESIAN = "bayesian", "Bayesian"
FREQUENTIST = "frequentist", "Frequentist"
+ class DeactivationReason(models.TextChoices):
+ UNPAID_BALANCE = "Access revoked due to unpaid balance.", "Unpaid balance"
+ COMPLIANCE_REVIEW = "Access disabled for compliance review.", "Compliance review"
+ TERMS_OF_SERVICE_VIOLATION = (
+ "Access revoked due to terms of service violation.",
+ "Terms of service violation",
+ )
+ DESKTOP_ABUSE = (
+ "Suspected PostHog Desktop abuse. Contact PostHog support if you think this is a mistake.",
+ "Desktop abuse",
+ )
+
members = models.ManyToManyField(
"posthog.User",
through="posthog.OrganizationMembership",
@@ -215,6 +227,8 @@ class Organization(ModelActivityMixin, UUIDTModel):
),
max_length=200,
)
+ # Transient flag set by the pre_save signal to communicate active-state changes to post_save.
+ _is_active_changed: bool = False
# Security / management settings
session_cookie_age = models.IntegerField(
@@ -597,6 +611,38 @@ def organization_about_to_be_created(sender, instance: Organization, raw, using,
instance.plugins_access_level = Organization.PluginsAccessLevel.ROOT
+@receiver(models.signals.pre_save, sender=Organization)
+def remember_organization_is_active_change(sender, instance: Organization, **kwargs):
+ instance._is_active_changed = False
+ if instance._state.adding:
+ return
+
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None and "is_active" not in update_fields:
+ return
+
+ previous_is_active = sender.objects.filter(pk=instance.pk).values_list("is_active", flat=True).first()
+ instance._is_active_changed = previous_is_active != instance.is_active
+
+
+@receiver(post_save, sender=Organization)
+def invalidate_llm_gateway_quota_cache_on_active_state_change(sender, instance: Organization, created: bool, **kwargs):
+ if created or not instance._is_active_changed:
+ return
+
+ organization_id = instance.pk
+
+ def _invalidate_cache():
+ from posthog.models.team import Team
+
+ from ee.billing.quota_limiting import invalidate_llm_gateway_quota_cache
+
+ team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))
+ invalidate_llm_gateway_quota_cache(team_ids)
+
+ transaction.on_commit(_invalidate_cache)
+
+
class OrganizationMembership(ModelActivityMixin, UUIDTModel):
class Level(models.IntegerChoices):
"""Keep in sync with TeamMembership.Level (only difference being projects not having an Owner)."""
diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.py
index cad025aae29b..76411ae8d812 100644
--- a/posthog/models/test/test_organization_model.py
+++ b/posthog/models/test/test_organization_model.py
@@ -13,6 +13,7 @@ from posthog.models import Organization, OrganizationInvite
from posthog.models.organization import BillingPeriod, OrganizationMembership
from posthog.plugins.test.mock import mocked_plugin_requests_get
from posthog.plugins.test.plugin_archives import HELLO_WORLD_PLUGIN_GITHUB_ZIP
+from posthog.redis import get_client
from products.cdp.backend.models.plugin import Plugin
@@ -435,6 +436,36 @@ class TestOrganization(BaseTest):
self.assertEqual(data["limited_teams"], [])
self.assertIsNone(data["redis_quota_limited_until"])
+ def test_is_active_change_invalidates_llm_gateway_quota_cache(self):
+ gateway_redis_url = "redis://llm-gateway-redis-org-active-test/"
+ second_team = self.organization.teams.create(name="Second Team", api_token="second_token")
+ other_organization = Organization.objects.create(name="Other Org")
+ other_team = other_organization.teams.create(name="Other Team", api_token="other_token")
+
+ billing_keys = [
+ f"quota:code_usage_billing:team:{self.team.id}",
+ f"quota:code_usage_billing:team:{second_team.id}",
+ ]
+ generation_keys = [
+ f"quota:generation:team:{self.team.id}",
+ f"quota:generation:team:{second_team.id}",
+ ]
+ other_generation_key = f"quota:generation:team:{other_team.id}"
+
+ with self.settings(LLM_GATEWAY_REDIS_URL=gateway_redis_url):
+ gateway_redis = get_client(gateway_redis_url)
+ gateway_redis.mset(dict.fromkeys(billing_keys, "stale"))
+ gateway_redis.set(other_generation_key, 4)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ self.organization.is_active = False
+ self.organization.save()
+
+ assert gateway_redis.mget(billing_keys) == [None] * len(billing_keys)
+ assert gateway_redis.mget(generation_keys) == [b"1"] * len(generation_keys)
+ assert gateway_redis.get(other_generation_key) == b"4"
+ gateway_redis.delete(other_generation_key)
+
@patch("ee.billing.quota_limiting.get_client")
def test_get_limited_products_no_limits(self, mock_get_client):
mock_redis = mock_get_client.return_value
diff --git a/posthog/templates/admin/posthog/organization/change_form.html b/posthog/templates/admin/posthog/organization/change_form.html
index c40932465671..1efbe1b33dbd 100644
--- a/posthog/templates/admin/posthog/organization/change_form.html
+++ b/posthog/templates/admin/posthog/organization/change_form.html
@@ -3,20 +3,18 @@
{% block extrahead %}
{{ block.super }}
+ {{ deactivation_reason_presets|json_script:"organization-deactivation-reason-presets" }}
<script nonce="{{ request.csp_nonce }}">
document.addEventListener("DOMContentLoaded", () => {
const isActiveCheckbox = document.getElementById("id_is_active")
const reasonField = document.getElementById("id_is_not_active_reason")
+ const presetsElement = document.getElementById("organization-deactivation-reason-presets")
- if (!isActiveCheckbox || !reasonField) {
+ if (!isActiveCheckbox || !reasonField || !presetsElement || !presetsElement.textContent) {
return
}
- const presets = [
- "Access revoked due to unpaid balance.",
- "Access disabled for compliance review.",
- "Access revoked due to terms of service violation.",
- ]
+ const presets = JSON.parse(presetsElement.textContent)
const reasonFieldRow = reasonField.closest(".form-row")
if (!reasonFieldRow) {
@@ -99,4 +97,4 @@
{% block submit_buttons_bottom %}
{{ block.super }}
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 163fad0084af..ea052c2db3c0 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -117,6 +117,7 @@ post_save:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__ini
post_save:posthog.models.file_system.user_product_list.access_control_created
post_save:posthog.models.global_rate_limit_threshold_config.update_redis_thresholds_on_save
post_save:posthog.models.organization.cache_organization_session_age
+post_save:posthog.models.organization.invalidate_llm_gateway_quota_cache_on_active_state_change
post_save:posthog.models.organization.sync_billing_on_membership_save
post_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_save
post_save:posthog.models.remote_config.error_tracking_suppression_rule_saved
@@ -230,6 +231,7 @@ pre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_de
pre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_type
pre_save:posthog.models.organization.organization_about_to_be_created
pre_save:posthog.models.organization.organization_membership_saved
+pre_save:posthog.models.organization.remember_organization_is_active_change
pre_save:posthog.models.product_intent.product_intent._capture_original_team_id
pre_save:posthog.models.user._pause_loops_on_user_deactivation
pre_save:posthog.models.user._revoke_sessions_on_user_deactivation
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 726f8ec68711..42373afcaa42 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -946,6 +946,13 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
{"detail": "The authoring task for this canvas no longer exists."},
status=status.HTTP_409_CONFLICT,
)
+ if outcome == "organization_deactivated":
+ return Response(
+ {
+ "detail": "Your organization has been deactivated. Contact PostHog support if you think this is a mistake."
+ },
+ status=status.HTTP_429_TOO_MANY_REQUESTS,
+ )
if outcome == "quota_exhausted":
return Response(
{"detail": "The team's compute quota is exhausted; retry later."},
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 0dec97a60ca1..2ab7a230a0fe 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -19,6 +20,7 @@ from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.canvas.backend import activity_visibility, build_service
from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion
from products.canvas.backend.source import synthetic_source_project
+from products.tasks.backend.logic.services.compute_quota import ComputeQuotaDenialReason
from products.tasks.backend.models import Channel, Task, TaskRun, TaskThreadMessage
@@ -1162,7 +1164,7 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):
super().setUp()
for target, value in (
("products.tasks.backend.facade.api._agent_thread_updates_enabled", True),
- ("products.tasks.backend.logic.services.compute_quota.is_compute_quota_exhausted", False),
+ ("products.tasks.backend.logic.services.compute_quota.get_compute_quota_denial_reason", None),
):
patcher = patch(target, return_value=value)
patcher.start()
@@ -1343,3 +1345,24 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):
build_id = str(CanvasBuild.objects.unscoped().get(canvas_id=canvas_id).id)
assert self._request_fix(canvas_id, build_id).status_code == status.HTTP_409_CONFLICT
+
+ @parameterized.expand(
+ [
+ ("deactivated", ComputeQuotaDenialReason.ORGANIZATION_DEACTIVATED, "deactivated"),
+ ("quota_exhausted", ComputeQuotaDenialReason.COMPUTE_QUOTA_EXHAUSTED, "compute quota"),
+ ]
+ )
+ def test_request_fix_reports_compute_denial_with_distinct_copy(self, _name, reason, expected_detail):
+ # A deactivated org must not be told the compute quota is exhausted and to
+ # retry later — a retry never clears deactivation.
+ canvas_id, build_id, _ = self._authored_canvas()
+
+ with patch(
+ "products.tasks.backend.logic.services.compute_quota.get_compute_quota_denial_reason",
+ return_value=reason,
+ ):
+ response = self._request_fix(canvas_id, build_id)
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS, response.json()
+ assert expected_detail in response.json()["detail"].lower()
+ assert not TaskRun.objects.exists()
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index b24b1d1b3d3a..12bc69dbb363 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -97,12 +97,18 @@ class SandboxProvisionError(ProcessTaskTransientError):
class ComputeBillingLimitError(ProcessTaskError, ComputeBillingLimitExceeded):
- def __init__(self, context: dict[str, Any]):
- from products.tasks.backend.logic.services.compute_quota import COMPUTE_QUOTA_DENIAL_CODE
-
+ def __init__(self, context: dict[str, Any], reason: str = "posthog_code_billing_limit_exceeded"):
+ from products.tasks.backend.logic.services.compute_quota import ORGANIZATION_DEACTIVATED_DENIAL_CODE
+
+ self.reason = reason
+ message = (
+ "Your organization has been deactivated."
+ if reason == ORGANIZATION_DEACTIVATED_DENIAL_CODE
+ else "Your organization reached its PostHog Desktop usage limit."
+ )
super().__init__(
- "Your organization reached its PostHog Desktop usage limit.",
- {**context, "reason": COMPUTE_QUOTA_DENIAL_CODE},
+ message,
+ {**context, "reason": reason},
None,
capture=False,
non_retryable=True,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index e97f13975114..3daa5f1bd346 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -3546,10 +3546,10 @@ def signal_task_run_user_message(
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
+ from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason # 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)})
+ if reason := get_compute_quota_denial_reason(run.task):
+ raise ComputeBillingLimitError({"team_id": team_id, "task_id": str(task_id), "run_id": str(run_id)}, reason)
try:
context = {"actor_slack_user_id": actor_slack_user_id} if actor_slack_user_id else None
signal_task_followup_message(
@@ -4756,11 +4756,13 @@ def create_task(
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
+ from products.tasks.backend.logic.services.compute_quota import ( # noqa: PLC0415
+ get_compute_quota_denial_reason,
+ )
- if is_compute_quota_exhausted(warm_task):
+ if reason := get_compute_quota_denial_reason(warm_task):
raise ComputeBillingLimitError(
- {"team_id": team_id, "task_id": str(warm_task.id), "run_id": str(warm_run.id)}
+ {"team_id": team_id, "task_id": str(warm_task.id), "run_id": str(warm_run.id)}, reason
)
description = (validated_data.get("description") or "").strip()
update_fields: list[str] = []
@@ -7381,6 +7383,19 @@ def post_canvas_error_thread_update(
return "skipped"
+def _canvas_fix_denial_outcome(reason: str) -> str:
+ """Map a compute-quota denial to a canvas fix outcome.
+
+ Deactivation and quota exhaustion need different copy: a retry clears a spent
+ quota but never a deactivation.
+ """
+ from products.tasks.backend.logic.services.compute_quota import ( # noqa: PLC0415
+ ORGANIZATION_DEACTIVATED_DENIAL_CODE,
+ )
+
+ return "organization_deactivated" if reason == ORGANIZATION_DEACTIVATED_DENIAL_CODE else "quota_exhausted"
+
+
def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting_user_id: int | None) -> str:
"""Wake a task's agent to fix a canvas: signal the live run, else seed a fresh run with ``prompt``.
@@ -7392,12 +7407,12 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting
create the run inside the transaction and dispatch its processing workflow
on commit with ``skip_user_check``.
Returns ``signaled`` / ``new_run`` / ``already_queued`` / ``not_found`` /
- ``forbidden`` / ``quota_exhausted``.
+ ``forbidden`` / ``quota_exhausted`` / ``organization_deactivated``.
"""
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
+ from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason # noqa: PLC0415
with transaction.atomic():
# of=("self",): FOR UPDATE cannot span the nullable created_by join.
@@ -7411,8 +7426,8 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting
return "not_found"
if acting_user_id is None or task.created_by_id != acting_user_id:
return "forbidden"
- if is_compute_quota_exhausted(task):
- return "quota_exhausted"
+ if reason := get_compute_quota_denial_reason(task):
+ return _canvas_fix_denial_outcome(reason)
run = task.latest_run
if run is not None and not run.is_terminal:
try:
@@ -7420,8 +7435,8 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting
run.id, task.id, team_id, content=prompt, artifact_ids=[], actor_user_id=acting_user_id
):
return "signaled"
- except ComputeBillingLimitError:
- return "quota_exhausted"
+ except ComputeBillingLimitError as error:
+ return _canvas_fix_denial_outcome(error.reason)
if run.status == TaskRun.Status.QUEUED and (run.state or {}).get("pending_user_message"):
# A queued, prompt-seeded run whose workflow hasn't registered yet
# is a fix run a just-committed request dispatched (creation is
diff --git a/products/tasks/backend/facade/compute_quota.py b/products/tasks/backend/facade/compute_quota.py
index c056713b36b7..0df57b40677b 100644
--- a/products/tasks/backend/facade/compute_quota.py
+++ b/products/tasks/backend/facade/compute_quota.py
@@ -1,2 +1,2 @@
class ComputeBillingLimitExceeded(Exception):
- pass
+ reason = "posthog_code_billing_limit_exceeded"
diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
index 53f70691312d..4d9185cf4e91 100644
--- a/products/tasks/backend/logic/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -12,7 +12,11 @@ from posthog.models import OAuthAccessToken
from posthog.temporal.oauth import create_oauth_access_token_for_user
from posthog.utils import get_instance_region
-from products.tasks.backend.logic.services.compute_quota import COMPUTE_QUOTA_DENIAL_CODE
+from products.tasks.backend.logic.services.compute_quota import (
+ COMPUTE_QUOTA_DENIAL_CODE,
+ ORGANIZATION_DEACTIVATED_DENIAL_CODE,
+ organization_deactivated,
+)
from products.tasks.backend.metrics import observe_code_usage_gate_check
from products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer
@@ -137,27 +141,42 @@ def rate_limit_error_payload(usage: CodeUsageStatus) -> dict[str, Any]:
return payload
-def compute_quota_limit_response() -> Response:
+def _billing_limit_response(code: str, error: str) -> Response:
return Response(
- TaskRunErrorResponseSerializer(
- {
- "type": "billing_limit",
- "code": COMPUTE_QUOTA_DENIAL_CODE,
- "error": "Your organization reached its PostHog Desktop usage limit.",
- }
- ).data,
+ TaskRunErrorResponseSerializer({"type": "billing_limit", "code": code, "error": error}).data,
status=status.HTTP_429_TOO_MANY_REQUESTS,
)
+def organization_deactivated_response() -> Response:
+ return _billing_limit_response(
+ ORGANIZATION_DEACTIVATED_DENIAL_CODE,
+ "Your organization has been deactivated. Contact PostHog support if you think this is a mistake.",
+ )
+
+
+def compute_quota_limit_response(reason: str = COMPUTE_QUOTA_DENIAL_CODE) -> Response:
+ if reason == ORGANIZATION_DEACTIVATED_DENIAL_CODE:
+ return organization_deactivated_response()
+ return _billing_limit_response(
+ COMPUTE_QUOTA_DENIAL_CODE,
+ "Your organization reached its PostHog Desktop usage limit.",
+ )
+
+
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.
Since Desktop moved to usage-based billing, this is the whole cost control on cloud runs —
no waitlist check is involved. Fails open when the gateway can't be reached, so every check
is counted by outcome (`checked_allowed` / `checked_blocked` / `fail_open`) and a degraded
- gateway silently removing the backstop is visible, not just logged.
+ gateway silently removing the backstop is visible, not just logged. Deactivated organizations
+ are blocked locally first, so that block holds even when the gateway check fails open.
"""
+ if organization_deactivated(team_id):
+ observe_code_usage_gate_check(outcome="org_deactivated")
+ return organization_deactivated_response()
+
usage = get_posthog_code_usage(user, team_id)
if usage is None:
observe_code_usage_gate_check(outcome="fail_open")
diff --git a/products/tasks/backend/logic/services/compute_quota.py b/products/tasks/backend/logic/services/compute_quota.py
index c3074c828428..4fa7191b6bef 100644
--- a/products/tasks/backend/logic/services/compute_quota.py
+++ b/products/tasks/backend/logic/services/compute_quota.py
@@ -1,14 +1,29 @@
import logging
+from enum import StrEnum
from django.conf import settings
+from posthog.models import Team
+
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"
+ORGANIZATION_DEACTIVATED_DENIAL_CODE = "organization_deactivated"
+
+
+class ComputeQuotaDenialReason(StrEnum):
+ COMPUTE_QUOTA_EXHAUSTED = COMPUTE_QUOTA_DENIAL_CODE
+ ORGANIZATION_DEACTIVATED = ORGANIZATION_DEACTIVATED_DENIAL_CODE
+
+
logger = logging.getLogger(__name__)
+def organization_deactivated(team_id: int) -> bool:
+ return Team.objects.filter(id=team_id, organization__is_active=False).exists()
+
+
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(
@@ -35,11 +50,14 @@ def is_billable_compute(
)
-def is_compute_quota_exhausted(task: Task) -> bool:
+def get_compute_quota_denial_reason(task: Task) -> ComputeQuotaDenialReason | None:
+ if organization_deactivated(task.team_id):
+ observe_compute_quota_check("checked_blocked")
+ return ComputeQuotaDenialReason.ORGANIZATION_DEACTIVATED
if not getattr(settings, "TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED", False):
- return False
+ return None
if not is_task_billable_compute(task):
- return False
+ return None
try:
exhausted = _is_posthog_code_quota_limited(task.team.api_token)
except Exception:
@@ -49,9 +67,13 @@ def is_compute_quota_exhausted(task: Task) -> bool:
extra={"team_id": task.team_id, "task_id": str(task.id)},
exc_info=True,
)
- return False
+ return None
observe_compute_quota_check("checked_blocked" if exhausted else "checked_allowed")
- return exhausted
+ return ComputeQuotaDenialReason.COMPUTE_QUOTA_EXHAUSTED if exhausted else None
+
+
+def is_compute_quota_exhausted(task: Task) -> bool:
+ return get_compute_quota_denial_reason(task) is not None
def _is_posthog_code_quota_limited(team_api_token: str) -> bool:
diff --git a/products/tasks/backend/logic/services/tests/test_compute_quota.py b/products/tasks/backend/logic/services/tests/test_compute_quota.py
index 1d9d05fb4533..c65979c0a56a 100644
--- a/products/tasks/backend/logic/services/tests/test_compute_quota.py
+++ b/products/tasks/backend/logic/services/tests/test_compute_quota.py
@@ -6,6 +6,8 @@ from django.test import override_settings
from posthog.models import Organization, Team
from products.tasks.backend.logic.services.compute_quota import (
+ ComputeQuotaDenialReason,
+ get_compute_quota_denial_reason,
is_billable_compute,
is_compute_quota_exhausted,
is_task_billable_compute,
@@ -37,6 +39,15 @@ class TestComputeQuota:
assert not is_compute_quota_exhausted(self.task())
limited.assert_not_called()
+ @override_settings(TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED=False)
+ def test_any_deactivated_org_blocks_even_with_enforcement_off(self):
+ self.team.organization.is_active = False
+ self.team.organization.is_not_active_reason = "Past due invoice"
+ self.team.organization.save()
+
+ assert is_compute_quota_exhausted(self.task())
+ assert get_compute_quota_denial_reason(self.task()) == ComputeQuotaDenialReason.ORGANIZATION_DEACTIVATED
+
@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):
diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.py
index ec9be05286c4..3032aaefcca0 100644
--- a/products/tasks/backend/logic/services/tests/test_warm.py
+++ b/products/tasks/backend/logic/services/tests/test_warm.py
@@ -119,6 +119,16 @@ class TestSandboxWarmerWarm(APIBaseTest):
assert task.runs.count() == 0
m_workflow.assert_not_called()
+ def test_deactivated_organization_creates_no_run(self):
+ self.organization.is_active = False
+ self.organization.save()
+ task = self._task()
+
+ with self.assertRaises(PermissionDenied):
+ SandboxWarmer(task, user=self.user).warm()
+
+ assert task.runs.count() == 0
+
def test_unregistered_origin_product_is_rejected(self):
# Fail-closed: only origin products with a registered quota gate may warm.
task = self._task(origin=Task.OriginProduct.ERROR_TRACKING)
diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.py
index bcf209fe6104..ab12837e2fc1 100644
--- a/products/tasks/backend/logic/services/warm.py
+++ b/products/tasks/backend/logic/services/warm.py
@@ -25,6 +25,7 @@ from posthog.exceptions import QuotaLimitExceeded
from posthog.models.team import Team
from posthog.models.user import User
+from products.tasks.backend.logic.services.compute_quota import organization_deactivated
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.client import execute_task_processing_workflow
from products.tasks.backend.temporal.process_task.utils import parse_run_state
@@ -98,6 +99,8 @@ class SandboxWarmer:
"""
if origin_product not in cls.ORIGIN_PRODUCT_QUOTA:
raise PermissionDenied(f"Warming is not enabled for origin product '{origin_product}'.")
+ if organization_deactivated(team.id):
+ raise PermissionDenied("Your organization has been deactivated.")
checker = cls.ORIGIN_PRODUCT_QUOTA[origin_product]
if checker is not None:
checker(team, user)
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index ab3b92c6c4ee..5da02552460e 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -221,12 +221,13 @@ LOOP_AUTO_PAUSED_TOTAL = Counter(
"Loops auto-paused after exceeding the consecutive-failure threshold",
)
-CodeUsageGateOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"]
+CodeUsageGateOutcome = Literal["checked_allowed", "checked_blocked", "fail_open", "org_deactivated"]
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:
-# a degraded gateway must not silently remove the only cost backstop).
+# a degraded gateway must not silently remove the only cost backstop), org_deactivated when
+# the local deactivated-organization check blocked the run before any gateway call.
CODE_USAGE_GATE_CHECK_TOTAL = Counter(
"posthog_tasks_code_usage_gate_check_total",
"Cloud usage-gate check outcomes for PostHog Code runs",
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 541a6117c02c..5f7261f71b3b 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -477,8 +477,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
validated_data=dict(serializer.validated_data),
client_provenance=get_task_client_provenance(request),
)
- except ComputeBillingLimitExceeded:
- return compute_quota_limit_response()
+ except ComputeBillingLimitExceeded as error:
+ return compute_quota_limit_response(error.reason)
self._forward_signals_discussion_note(request, task, relationship)
return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)
@@ -2107,8 +2107,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 ComputeBillingLimitExceeded as error:
+ return compute_quota_limit_response(error.reason)
except Exception:
# A synchronous web request can't retry the way the Temporal
# follow-up path does, so a transient signalling failure surfaces
diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.py
index 100b4e7033c5..40cf66a08b3f 100644
--- a/products/tasks/backend/presentation/views/channels_api.py
+++ b/products/tasks/backend/presentation/views/channels_api.py
@@ -581,8 +581,8 @@ class TaskThreadMessageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def send_to_agent(self, request, pk=None, **kwargs):
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()
+ except ComputeBillingLimitExceeded as error:
+ return compute_quota_limit_response(error.reason)
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.py
index 5595e9b0c289..c8a2f0401fd1 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
@@ -106,11 +106,11 @@ def forward_pending_user_message(run_id: str) -> None:
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
+ from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason
- if is_compute_quota_exhausted(task_run.task):
+ if reason := get_compute_quota_denial_reason(task_run.task):
raise ComputeBillingLimitError(
- {"team_id": task_run.team_id, "task_id": str(task_run.task_id), "run_id": run_id}
+ {"team_id": task_run.team_id, "task_id": str(task_run.task_id), "run_id": run_id}, reason
)
pending_message_id = state.get("pending_user_message_id")
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 08a51882ca35..55e5fca32144 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -27,7 +27,7 @@ from products.tasks.backend.exceptions import (
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_exhausted
+from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason
from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
@@ -615,10 +615,12 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
image_source=prepared.image_source,
**ctx.to_log_context(),
):
- if settings.TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED and not (ctx.state or {}).get("await_user_message"):
+ if 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})
+ if reason := get_compute_quota_denial_reason(task):
+ raise ComputeBillingLimitError(
+ {"team_id": ctx.team_id, "task_id": ctx.task_id, "run_id": ctx.run_id}, reason
+ )
_emit_image_source_log(ctx, prepared)
emit_agent_log(
ctx.run_id,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 7e1b485fef8a..9492dbea9d94 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -11158,6 +11158,24 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertTrue(TaskRun.objects.filter(task=task).exists())
mock_workflow.assert_called_once()
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_run_for_any_deactivated_org_returns_429_without_gateway_check(self, mock_gate):
+ self.organization.is_active = False
+ self.organization.is_not_active_reason = "Past due invoice"
+ self.organization.save()
+ task = self.create_task()
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"mode": "background"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertEqual(response.json()["code"], "organization_deactivated")
+ self.assertFalse(TaskRun.objects.filter(task=task).exists())
+ mock_gate.assert_not_called()
+
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_run_over_limit_returns_429_and_creates_no_run(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
@@ -11374,7 +11392,7 @@ class TestGetPosthogCodeUsage(TestCase):
mock_token.assert_not_called()
-class TestUsageLimitResponse(SimpleTestCase):
+class TestUsageLimitResponse(TestCase):
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_over_limit_response_is_structured(self, mock_usage):
mock_usage.return_value = CodeUsageStatus(
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 19707eb2062e..4c58e2441881 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -486,7 +486,10 @@ class TestCreateTaskWarmReuse(APIBaseTest):
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):
+ with patch(
+ "products.tasks.backend.logic.services.compute_quota.get_compute_quota_denial_reason",
+ return_value="posthog_code_billing_limit_exceeded",
+ ):
response = self.client.post(
"/api/projects/@current/tasks/",
{"description": "fix the bug", "repository": "posthog/posthog", "branch": "main"},
diff --git a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
index 86ee5fb33f08..d146eba5e7c0 100644
--- a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
+import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -127,9 +128,9 @@ class _PermanentUpstreamError(Exception):
"""Non-retryable failure: a 4xx response — bad token, missing team, scope mismatch."""
-def _redis_key(resource_key: str, team_id: int, auth_header: str) -> str:
+def _redis_key(resource_key: str, team_id: int, auth_header: str, generation: str = "0") -> str:
credential_fingerprint = hashlib.sha256(auth_header.encode()).hexdigest()
- return f"quota:{resource_key}:team:{team_id}:credential:{credential_fingerprint}"
+ return f"quota:{resource_key}:team:{team_id}:generation:{generation}:credential:{credential_fingerprint}"
def _billing_key(team_id: int) -> str:
@@ -138,6 +139,10 @@ def _billing_key(team_id: int) -> str:
return f"quota:code_usage_billing:team:{team_id}"
+def _generation_key(team_id: int) -> str:
+ return f"quota:generation:team:{team_id}"
+
+
async def resolve_quota_status(request: Request, team_id: int | None, resource_key: str) -> QuotaResourceStatus:
"""Resolve the team's quota state for one resource, falling open on errors."""
if team_id is None:
@@ -166,7 +171,8 @@ class QuotaResolver:
self._cache_ttl = get_settings().quota_cache_ttl
async def get_resource_status(self, resource_key: str, team_id: int, auth_header: str) -> QuotaResourceStatus:
- cached = await self._get_cached(resource_key, team_id, auth_header)
+ generation = await self._get_generation(team_id)
+ cached = await self._get_cached(resource_key, team_id, auth_header, generation)
if cached is not None:
return cached
@@ -192,7 +198,7 @@ class QuotaResolver:
_FAIL_OPEN_CACHE_TTL_SECONDS,
)
- await self._set_cached(resource_key, team_id, auth_header, status, ttl)
+ await self._set_cached(resource_key, team_id, auth_header, generation, status, ttl)
return status
async def _fetch_with_retry(
@@ -247,11 +253,23 @@ class QuotaResolver:
posthog_desktop_usage=_posthog_desktop_usage(data) if resource_key == "posthog_code_credits" else None,
), self._cache_ttl
- async def _get_cached(self, resource_key: str, team_id: int, auth_header: str) -> QuotaResourceStatus | None:
+ async def _get_generation(self, team_id: int) -> str:
+ if not self._redis:
+ return "0"
+ try:
+ value = await self._redis.get(_generation_key(team_id))
+ return value.decode() if value is not None else "0"
+ except Exception:
+ logger.debug("quota_generation_read_failed", team_id=team_id)
+ return uuid.uuid4().hex
+
+ async def _get_cached(
+ self, resource_key: str, team_id: int, auth_header: str, generation: str
+ ) -> QuotaResourceStatus | None:
if not self._redis:
return None
try:
- val = await self._redis.get(_redis_key(resource_key, team_id, auth_header))
+ val = await self._redis.get(_redis_key(resource_key, team_id, auth_header, generation))
if val is None:
return None
payload = json.loads(val.decode())
@@ -271,7 +289,13 @@ class QuotaResolver:
return None
async def _set_cached(
- self, resource_key: str, team_id: int, auth_header: str, status: QuotaResourceStatus, ttl: int
+ self,
+ resource_key: str,
+ team_id: int,
+ auth_header: str,
+ generation: str,
+ status: QuotaResourceStatus,
+ ttl: int,
) -> None:
if not self._redis:
return
@@ -289,7 +313,7 @@ class QuotaResolver:
),
}
)
- await self._redis.set(_redis_key(resource_key, team_id, auth_header), payload, ex=ttl)
+ await self._redis.set(_redis_key(resource_key, team_id, auth_header, generation), payload, ex=ttl)
except Exception:
logger.debug("quota_cache_write_failed", resource=resource_key, team_id=team_id)
diff --git a/services/llm-gateway/tests/test_quota_resolver.py b/services/llm-gateway/tests/test_quota_resolver.py
index 08d9bf27713c..fc510736ce7b 100644
--- a/services/llm-gateway/tests/test_quota_resolver.py
+++ b/services/llm-gateway/tests/test_quota_resolver.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import json
from collections.abc import Iterator
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
import httpx
import pytest
@@ -15,6 +15,7 @@ from llm_gateway.services.quota_resolver import (
QuotaResolver,
QuotaResourceStatus,
_billing_key,
+ _generation_key,
_redis_key,
resolve_quota_status,
)
@@ -495,16 +496,33 @@ class TestQuotaResolver:
@pytest.mark.asyncio
async def test_uses_cached_result_and_skips_http(self) -> None:
redis = AsyncMock()
- redis.get = AsyncMock(return_value=json.dumps({"limited": True}).encode())
+ redis.get = AsyncMock(side_effect=[b"7", json.dumps({"limited": True}).encode()])
http_client = _make_http_client(_make_response(200))
resolver = QuotaResolver(redis=redis, http_client=http_client)
status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")
assert status == QuotaResourceStatus(limited=True)
- redis.get.assert_awaited_once_with(_redis_key("ai_credits", 42, "Bearer phx_test"))
+ assert redis.get.await_args_list == [
+ call(_generation_key(42)),
+ call(_redis_key("ai_credits", 42, "Bearer phx_test", "7")),
+ ]
http_client.get.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_generation_change_bypasses_cached_result(self) -> None:
+ redis = _FakeRedis()
+ http_client = _make_http_client(_make_response(200, {"limited": {"ai_credits": {"limited": True}}}))
+ resolver = QuotaResolver(redis=redis, http_client=http_client) # type: ignore[arg-type]
+
+ first = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")
+ redis.store[_generation_key(42)] = b"1"
+ second = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")
+
+ assert first.limited is True
+ assert second.limited is True
+ assert http_client.get.await_count == 2
+
@pytest.mark.asyncio
async def test_writes_cache_on_miss(self) -> None:
redis = AsyncMock()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 70549712100a..68c2772b7f54 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66948,7 +66948,7 @@ export namespace Schemas {
}
export interface QuotaResourceLimit {
- /** True when the team is currently over its quota for this resource and limits are in effect. */
+ /** True when the team is currently over its quota for this resource and limits are in effect. A deactivated organization additionally reads as limited on the two credit buckets `ai_credits` and `posthog_code_credits`, regardless of usage. */
limited: boolean;
/**
* Units of this resource the organization has used so far this billing period, in the resource's native unit (credits for credit buckets). Null when billing hasn't synced usage for the resource.
@@ -66970,7 +66970,7 @@ export namespace Schemas {
export interface QuotaLimitsResponse {
/** Per-resource limit state for every `QuotaResource` value, e.g. `ai_credits`, `posthog_code_credits`. Also carries the informational Desktop component resources (`posthog_code_token_credits`, `sandbox_compute_credits`, `sandbox_compute_cpu_millicore_seconds`, `sandbox_compute_memory_mib_seconds`) with usage in their native units, a null limit, and `limited` always false — they are never quota-enforced; only the combined `posthog_code_credits` is. */
limited: QuotaLimitsResponseLimited;
- /** Whether the team's organization pays for PostHog Desktop usage: billing grants the `posthog_code_usage` product feature only on the Desktop usage product's paid plan, synced into the organization's available features. Consumers gate paid-tier Desktop behavior on this; an org unknown to billing reads as not paying. */
+ /** Whether the team's organization pays for PostHog Desktop usage: billing grants the `posthog_code_usage` product feature only on the Desktop usage product's paid plan, synced into the organization's available features. Consumers gate paid-tier Desktop behavior on this; an org unknown to billing reads as not paying. Always false for deactivated organizations. */
code_usage_billing_active: boolean;
}