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.

feat(tasks): route posthog code through the ai gateway behind a flag (#106213)

Brandon33c805f9e113
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index eacd9d3f8643..e9a9f7f79fd2 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -188,13 +188,12 @@ per-run dollar cap. Two JSON object settings can override it:
- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES` maps team IDs to caps.
- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES` maps AI product names to
- caps and defaults to
- `{"signals_implementation": "15", "signals_inbox": "75", "signals_chat": "30"}`.
+ caps. It is merged onto the built-in `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_DEFAULTS`
+ map in `posthog/settings/temporal.py`, and its entry wins per product.
-A product override takes precedence over a team override, which takes precedence
-over the default cap. Set the product override to `{}` to disable the built-in
-implementation override. An empty environment value is treated as unset and
-restores the built-in map.
+A product cap takes precedence over a team override, which takes precedence over
+the default cap. An invalid entry, or a value that is not a JSON object, is
+reported to error tracking and ignored, so the product keeps its built-in cap.
### Which gateway a sandbox run uses
diff --git a/ee/api/quota_limits.py b/ee/api/quota_limits.py
index b62ad2ccd874..24afb4c85d68 100644
--- a/ee/api/quota_limits.py
+++ b/ee/api/quota_limits.py
@@ -18,9 +18,8 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.constants import AvailableFeature
-from ee.billing.quota_limiting import INFORMATIONAL_USAGE_RESOURCES, QuotaResource, get_fresh_team_limited_resources
+from ee.billing.quota_limiting import team_quota_snapshot
class QuotaResourceLimitSerializer(serializers.Serializer):
@@ -45,22 +44,6 @@ class QuotaResourceLimitSerializer(serializers.Serializer):
)
-def _resource_usage(summary: dict[str, Any]) -> float | None:
- """usage + todays_usage, the sum the quota limiter compares against the limit.
-
- None rather than 0 when billing has never synced the resource, so clients read
- it as unknown, not "$0 spent". The `limited` boolean stays authoritative for
- gating; grace periods and refund offsets live only in that limiting decision.
- """
- if not summary:
- return None
- usage = summary.get("usage")
- todays_usage = summary.get("todays_usage")
- if usage is None and todays_usage is None:
- return None
- return (usage or 0) + (todays_usage or 0)
-
-
class QuotaLimitsResponseSerializer(serializers.Serializer):
limited = serializers.DictField(
child=QuotaResourceLimitSerializer(),
@@ -102,38 +85,5 @@ class QuotaLimitsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
responses={200: QuotaLimitsResponseSerializer},
)
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.
- # 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 {}
- limited[resource.value] = {
- "limited": limited_resources[resource],
- "usage": _resource_usage(summary),
- "limit": summary.get("limit"),
- }
- for field in INFORMATIONAL_USAGE_RESOURCES:
- limited[field] = {
- "limited": False,
- "usage": _resource_usage(org_usage.get(field) or {}),
- "limit": None,
- }
- data = QuotaLimitsResponseSerializer(
- {
- "limited": limited,
- "code_usage_billing_active": not org_deactivated
- and self.team.organization.is_feature_available(AvailableFeature.POSTHOG_CODE_USAGE),
- }
- ).data
+ data = QuotaLimitsResponseSerializer(team_quota_snapshot(self.team)).data
return Response(data)
diff --git a/ee/api/test/test_quota_limits.py b/ee/api/test/test_quota_limits.py
index 0ed5e4232067..d48341ca644f 100644
--- a/ee/api/test/test_quota_limits.py
+++ b/ee/api/test/test_quota_limits.py
@@ -69,7 +69,7 @@ class TestQuotaLimitsAPI(APIBaseTest):
# The deactivated-org answer must not depend on Redis being reachable.
with patch(
- "ee.api.quota_limits.get_fresh_team_limited_resources",
+ "ee.billing.quota_limiting.get_fresh_team_limited_resources",
side_effect=Exception("redis unavailable"),
):
response = self.client.get(self._url())
diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.py
index f1fd6d9274d9..4f7cd3138bce 100644
--- a/ee/billing/quota_limiting.py
+++ b/ee/billing/quota_limiting.py
@@ -18,7 +18,7 @@ import posthoganalytics
from posthog.cache_utils import cache_for
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.constants import FlagRequestType
+from posthog.constants import AvailableFeature, FlagRequestType
from posthog.dataclasses import frozen
from posthog.event_usage import report_organization_action
from posthog.exceptions_capture import capture_exception
@@ -286,6 +286,48 @@ def get_fresh_team_limited_resources(team_api_token: str) -> dict[QuotaResource,
return {resource: score is not None and score >= now_ts for resource, score in zip(QuotaResource, scores)}
+def _resource_usage(summary: dict[str, Any]) -> float | None:
+ """None when billing never synced the resource, so clients read unknown usage. Gate on
+ `limited`: grace periods and refund offsets apply only there."""
+ if not summary:
+ return None
+ usage = summary.get("usage")
+ todays_usage = summary.get("todays_usage")
+ if usage is None and todays_usage is None:
+ return None
+ return (usage or 0) + (todays_usage or 0)
+
+
+def team_quota_snapshot(team: Team) -> dict[str, Any]:
+ """Reads Redis fresh because the legacy gateway re-caches this for minutes, and the 30s memo would
+ re-poison a just-invalidated entry. A deactivated org is limited only on the gateway credit buckets,
+ which blocks AI spend without dropping events."""
+ organization = team.organization
+ org_usage = organization.usage or {}
+ org_deactivated = organization.is_active is False
+ 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(team.api_token)
+ limited: dict[str, dict[str, Any]] = {}
+ for resource in QuotaResource:
+ summary = org_usage.get(resource.value) or {}
+ limited[resource.value] = {
+ "limited": limited_resources[resource],
+ "usage": _resource_usage(summary),
+ "limit": summary.get("limit"),
+ }
+ for field in INFORMATIONAL_USAGE_RESOURCES:
+ limited[field] = {"limited": False, "usage": _resource_usage(org_usage.get(field) or {}), "limit": None}
+ return {
+ "limited": limited,
+ "code_usage_billing_active": not org_deactivated
+ and organization.is_feature_available(AvailableFeature.POSTHOG_CODE_USAGE),
+ }
+
+
def dispatch_recordings_remote_config_sync(team_ids: Iterable[int]) -> None:
"""
Triggers a `RemoteConfig` rebuild for each team after its recordings quota-limit state
@@ -305,11 +347,67 @@ def dispatch_recordings_remote_config_sync(team_ids: Iterable[int]) -> None:
capture_exception(e, {"team_id": team_id})
-def is_team_over_ai_credit_budget(team_api_token: str) -> bool:
- """Single AI-credit quota signal for LLM-spending paths to share — one resource + cache-key
- pair. On a cache miss this issues a synchronous Redis read, so async callers must wrap it in
+def is_team_over_credit_budget(team_api_token: str, resource: QuotaResource) -> bool:
+ """Quota signal for an LLM-spending path billed into `resource` (an AI credit bucket). On a
+ cache miss this issues a synchronous Redis read, so async callers must wrap it in
sync_to_async."""
- return is_team_limited(team_api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+ return is_team_limited(team_api_token, resource, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+
+def is_team_over_ai_credit_budget(team_api_token: str) -> bool:
+ return is_team_over_credit_budget(team_api_token, QuotaResource.AI_CREDITS)
+
+
+def get_teams_limited_until(team_api_tokens: Iterable[str], resources: Iterable[str]) -> dict[str, dict[str, float]]:
+ tokens = list(team_api_tokens)
+ names = list(resources)
+ now_ts = timezone.now().timestamp()
+ pipe = get_client().pipeline()
+ for token in tokens:
+ for name in names:
+ pipe.zscore(f"{QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY.value}{name}", token)
+ scores = iter(pipe.execute())
+ return {
+ token: {
+ name: float(score)
+ for name, score in ((name, next(scores)) for name in names)
+ if score is not None and score >= now_ts
+ }
+ for token in tokens
+ }
+
+
+def get_team_limited_until(team_api_token: str, resources: Iterable[str]) -> dict[str, float]:
+ return get_teams_limited_until([team_api_token], resources)[team_api_token]
+
+
+_LLM_GATEWAY_PROJECTION_BATCH = 500
+
+
+def _project_llm_gateway_quota_for_org(organization: Organization) -> None:
+ """Best-effort because the billing GET reaches this: an enqueue failure must not fail the update."""
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return
+ try:
+ from posthog.tasks.team_llm_gateway_quota import project_org_llm_gateway_quota_task # noqa: PLC0415
+
+ project_org_llm_gateway_quota_task.delay(str(organization.id))
+ except Exception as e:
+ capture_exception(e)
+
+
+def _project_llm_gateway_quota_for_tokens(tokens: Iterable[str]) -> None:
+ """Enqueued so the all-orgs run never waits on the ai-gateway Redis; the reconcile heals a lost batch."""
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return
+ from posthog.tasks.team_llm_gateway_quota import project_teams_llm_gateway_quota_task # noqa: PLC0415
+
+ token_list = sorted({token for token in tokens if token})
+ for start in range(0, len(token_list), _LLM_GATEWAY_PROJECTION_BATCH):
+ try:
+ project_teams_llm_gateway_quota_task.delay(token_list[start : start + _LLM_GATEWAY_PROJECTION_BATCH])
+ except Exception as e:
+ capture_exception(e)
# -------------------------------------------------------------------------------------------------
@@ -798,6 +896,7 @@ def update_org_billing_quotas(organization: Organization):
dispatch_recordings_remote_config_sync(recordings_transitioned_team_ids)
invalidate_llm_gateway_quota_cache(teams_by_token.values())
+ _project_llm_gateway_quota_for_org(organization)
def refresh_org_self_driving_quota(organization_id: str) -> None:
@@ -1538,6 +1637,15 @@ def update_all_orgs_billing_quotas(
quota_limiting_suspended_teams[field],
QuotaLimitingCaches.QUOTA_LIMITING_SUSPENDED_KEY,
)
+ # Re-project every team limited before or after this run: the blob TTL is the limit's end,
+ # which can move for a team that stays limited.
+ changed_ai_tokens: set[str] = set()
+ for resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ changed_ai_tokens |= set(previously_quota_limited_team_tokens[resource.value]) | set(
+ quota_limited_teams[resource.value]
+ )
+ if changed_ai_tokens:
+ _project_llm_gateway_quota_for_tokens(changed_ai_tokens)
redis_duration_s = round((time() - redis_start), 1)
logger.info("quota_limiting_run", phase="redis", status="done", duration_ms=round(redis_duration_s * 1000, 1))
if progress_callback:
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index ac12f866cfb7..b014a4d2605f 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -34,6 +34,7 @@ from ee.billing.quota_limiting import (
list_limited_team_attributes,
org_quota_limited_until,
refresh_org_self_driving_quota,
+ remove_limited_team_tokens,
replace_limited_team_tokens,
set_org_usage_summary,
update_all_orgs_billing_quotas,
@@ -3255,3 +3256,220 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):
with patch("ee.billing.quota_limiting.get_self_driving_credits_used_in_period_for_org") as live_mock:
refresh_org_self_driving_quota(str(self.organization.id))
live_mock.assert_not_called()
+
+
+@override_settings(CLOUD_DEPLOYMENT="US", AI_GATEWAY_REDIS_URL="redis://localhost:6379/15")
+class TestLLMGatewayQuotaProjectionHooks(BaseTest):
+ _GATEWAY_REDIS_URL = "redis://localhost:6379/15"
+
+ def setUp(self):
+ super().setUp()
+ from posthog.storage.team_llm_gateway_quota_cache import team_llm_gateway_quota_hypercache
+
+ team_llm_gateway_quota_hypercache.cache_client.clear()
+ for resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ remove_limited_team_tokens(resource, [self.team.api_token], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+ def tearDown(self):
+ for resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ remove_limited_team_tokens(resource, [self.team.api_token], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+ super().tearDown()
+
+ @patch("posthog.tasks.team_llm_gateway_quota.settings")
+ @patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
+ def test_update_org_billing_quotas_projects_then_lifts_the_gateway_quota_blob(
+ self, mock_settings, task_settings
+ ) -> None:
+ from posthog.storage.team_llm_gateway_quota_cache import get_team_quota_blob
+
+ mock_settings.AI_GATEWAY_REDIS_URL = self._GATEWAY_REDIS_URL
+ task_settings.AI_GATEWAY_REDIS_URL = self._GATEWAY_REDIS_URL
+ other_team = create_team(organization=self.organization)
+ with self.settings(USE_TZ=False):
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "ai_credits": {"usage": 1_000, "limit": 100, "todays_usage": 0},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+ self.organization.customer_trust_scores = zero_trust_scores()
+ self.organization.save()
+
+ update_org_billing_quotas(self.organization)
+
+ for team in (self.team, other_team):
+ blob = get_team_quota_blob(team)
+ assert blob is not None, team.id
+ assert blob["team_id"] == team.id
+ assert blob["buckets"]["ai_credits"]["limited"] is True
+ assert "posthog_code_credits" not in blob["buckets"]
+ assert blob["org_deactivated"] is False
+
+ self.organization.usage["ai_credits"]["limit"] = 10_000
+ self.organization.save()
+ update_org_billing_quotas(self.organization)
+
+ for team in (self.team, other_team):
+ assert get_team_quota_blob(team) is None, team.id
+
+ @patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+ def test_update_org_billing_quotas_projection_failure_does_not_fail_billing(self, mock_settings) -> None:
+ mock_settings.AI_GATEWAY_REDIS_URL = self._GATEWAY_REDIS_URL
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+ with (
+ patch(
+ "posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay",
+ side_effect=RuntimeError("broker down"),
+ ) as delay,
+ patch("ee.billing.quota_limiting.capture_exception") as capture,
+ ):
+ update_org_billing_quotas(self.organization)
+ delay.assert_called_once_with(str(self.organization.id))
+ capture.assert_called_once()
+
+ @parameterized.expand([("live_run_projects", False, True), ("dry_run_projects_nothing", True, False)])
+ @patch("ee.billing.quota_limiting._project_llm_gateway_quota_for_tokens")
+ @patch("posthoganalytics.capture")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
+ def test_update_all_orgs_billing_quotas_projects_the_ai_zset_diff(
+ self, _name, dry_run, expect_projection, _capture, project
+ ) -> None:
+ with self.settings(USE_TZ=False):
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "posthog_code_credits": {"usage": 5_000, "limit": 100, "todays_usage": 0},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+ self.organization.customer_trust_scores = zero_trust_scores()
+ self.organization.save()
+
+ update_all_orgs_billing_quotas(dry_run=dry_run)
+
+ if not expect_projection:
+ project.assert_not_called()
+ return
+ project.assert_called_once()
+ (tokens,) = project.call_args.args
+ assert self.team.api_token in tokens
+
+ @patch("ee.billing.quota_limiting._project_llm_gateway_quota_for_tokens")
+ @patch("posthoganalytics.capture")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
+ def test_update_all_orgs_billing_quotas_reprojects_a_lifted_team(self, _capture, project) -> None:
+ add_limited_team_tokens(
+ QuotaResource.POSTHOG_CODE_CREDITS,
+ {self.team.api_token: 1611900000},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+ with self.settings(USE_TZ=False):
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "posthog_code_credits": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+ self.organization.customer_trust_scores = zero_trust_scores()
+ self.organization.save()
+
+ update_all_orgs_billing_quotas()
+
+ project.assert_called_once()
+ (tokens,) = project.call_args.args
+ assert self.team.api_token in tokens
+
+ def test_the_all_orgs_projection_is_enqueued_in_batches_not_run_inline(self) -> None:
+ from ee.billing.quota_limiting import _project_llm_gateway_quota_for_tokens
+
+ tokens = [f"phc_{i:04d}" for i in range(1_001)] + ["", "phc_0000"]
+ with (
+ patch("posthog.tasks.team_llm_gateway_quota.project_teams_llm_gateway_quota_task.delay") as delay,
+ patch("posthog.storage.team_llm_gateway_quota_cache.project_teams_quota_by_token") as inline,
+ ):
+ _project_llm_gateway_quota_for_tokens(tokens)
+ inline.assert_not_called()
+ batches = [call.args[0] for call in delay.call_args_list]
+ assert [len(batch) for batch in batches] == [500, 500, 1]
+ assert sorted(token for batch in batches for token in batch) == sorted(set(tokens) - {""})
+
+ def test_nothing_is_enqueued_without_gateway_redis_url(self) -> None:
+ from ee.billing.quota_limiting import _project_llm_gateway_quota_for_org, _project_llm_gateway_quota_for_tokens
+
+ with (
+ self.settings(AI_GATEWAY_REDIS_URL=None),
+ patch("posthog.tasks.team_llm_gateway_quota.project_teams_llm_gateway_quota_task.delay") as teams_delay,
+ patch("posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay") as org_delay,
+ ):
+ _project_llm_gateway_quota_for_tokens([self.team.api_token])
+ _project_llm_gateway_quota_for_org(self.organization)
+ teams_delay.assert_not_called()
+ org_delay.assert_not_called()
+
+ def test_an_enqueue_failure_is_captured_not_raised(self) -> None:
+ from ee.billing.quota_limiting import _project_llm_gateway_quota_for_tokens
+
+ with (
+ patch(
+ "posthog.tasks.team_llm_gateway_quota.project_teams_llm_gateway_quota_task.delay",
+ side_effect=RuntimeError("broker down"),
+ ),
+ patch("ee.billing.quota_limiting.capture_exception") as capture,
+ ):
+ _project_llm_gateway_quota_for_tokens([self.team.api_token])
+ capture.assert_called_once()
+
+ def test_one_failed_enqueue_does_not_skip_the_later_batches(self) -> None:
+ from ee.billing.quota_limiting import _project_llm_gateway_quota_for_tokens
+
+ with (
+ patch(
+ "posthog.tasks.team_llm_gateway_quota.project_teams_llm_gateway_quota_task.delay",
+ side_effect=[RuntimeError("broker blip"), None, None],
+ ) as delay,
+ patch("ee.billing.quota_limiting.capture_exception") as capture,
+ ):
+ _project_llm_gateway_quota_for_tokens([f"phc_{i:04d}" for i in range(1_001)])
+ assert delay.call_count == 3
+ capture.assert_called_once()
+
+ @parameterized.expand(
+ [
+ ("ai_credits", QuotaResource.AI_CREDITS, True),
+ ("posthog_code_credits", QuotaResource.POSTHOG_CODE_CREDITS, True),
+ ("events", QuotaResource.EVENTS, False),
+ ]
+ )
+ def test_staff_limit_and_unlimit_reproject_only_ai_buckets(self, _name, resource, expect_projection) -> None:
+ self.organization.usage = {"period": ["2021-01-01T00:00:00Z", "2099-01-31T23:59:59Z"]}
+ self.organization.save()
+ with patch("posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay") as delay:
+ self.organization.limit_product_until_end_of_billing_cycle(resource)
+ self.organization.unlimit_product(resource)
+ assert delay.call_count == (2 if expect_projection else 0)
+
+ @patch("ee.billing.quota_limiting._project_llm_gateway_quota_for_tokens")
+ @patch("posthoganalytics.capture")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
+ def test_update_all_orgs_billing_quotas_reprojects_a_team_that_stays_limited(self, _capture, project) -> None:
+ add_limited_team_tokens(
+ QuotaResource.POSTHOG_CODE_CREDITS,
+ {self.team.api_token: 1611900000},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+ with self.settings(USE_TZ=False):
+ self.organization.usage = {
+ "events": {"usage": 1, "limit": 100, "todays_usage": 0},
+ "posthog_code_credits": {"usage": 5_000, "limit": 100, "todays_usage": 0},
+ "period": ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"],
+ }
+ self.organization.customer_trust_scores = zero_trust_scores()
+ self.organization.save()
+
+ update_all_orgs_billing_quotas()
+
+ project.assert_called_once()
+ (tokens,) = project.call_args.args
+ assert self.team.api_token in tokens
+ members = {m.decode("utf-8") for m in get_client().zrange("@posthog/quota-limits/posthog_code_credits", 0, -1)}
+ assert self.team.api_token in members
diff --git a/posthog/management/commands/llm_gateway_team.py b/posthog/management/commands/llm_gateway_team.py
index 197340dc9900..a5029420da4d 100644
--- a/posthog/management/commands/llm_gateway_team.py
+++ b/posthog/management/commands/llm_gateway_team.py
@@ -11,6 +11,8 @@ Usage:
python manage.py llm_gateway_team clear-allowance 42
python manage.py llm_gateway_team refresh 42
python manage.py llm_gateway_team status 42
+ python manage.py llm_gateway_team project-quota 42
+ python manage.py llm_gateway_team project-quota --all
The admission fields and llm_gateway_overspend_allowance_usd live on Team.
enabled_at/revoked_at project into the dedicated llm_gateway_policy blob;
@@ -22,12 +24,21 @@ handlers. The gateway admits a team only when enabled_at is set and revoked_at i
from decimal import Decimal, InvalidOperation
from typing import Any
+from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from posthog.models.team.team import Team
from posthog.storage.gateway_credential_cache import validate_overspend_allowance_usd
from posthog.storage.team_llm_gateway_policy_cache import update_team_llm_gateway_policy_cache
+from posthog.storage.team_llm_gateway_quota_cache import (
+ AI_GATEWAY_QUOTA_BUCKETS,
+ get_team_quota_blob,
+ project_team_quota,
+ quota_blob_ttl_remaining,
+ reconcile_quota_projection,
+ team_llm_gateway_quota_hypercache,
+)
_VERBS = (
("enable", "set llm_gateway_enabled_at to now (idempotent: no-op if already set)"),
@@ -38,6 +49,7 @@ _VERBS = (
("clear-allowance", "clear llm_gateway_overspend_allowance_usd (unset → gateway falls back to its default)"),
("refresh", "rewrite the team's policy cache entry from current DB state (no field change)"),
("status", "print the team's current admission state"),
+ ("project-quota", "write or clear the team's llm_gateway_quota blob from the quota zsets and org state"),
)
@@ -48,13 +60,20 @@ class Command(BaseCommand):
sub = parser.add_subparsers(dest="action", required=True, metavar="action")
for verb, desc in _VERBS:
p = sub.add_parser(verb, help=desc)
+ if verb == "project-quota":
+ p.add_argument("team", nargs="?", help="team id (integer) or api_token")
+ p.add_argument("--all", action="store_true", help="reconcile every limited or projected team")
+ continue
p.add_argument("team", help="team id (integer) or api_token")
if verb == "set-allowance":
p.add_argument("usd", help="allowance in USD, e.g. 5 or 5.000000 (0–10000, max 6 dp)")
def handle(self, *args: Any, **opts: Any) -> None:
- team = _resolve_team(opts["team"])
action = opts["action"]
+ if action == "project-quota":
+ self._project_quota(opts)
+ return
+ team = _resolve_team(opts["team"])
if action == "status":
_print_status(self.stdout, team)
return
@@ -85,6 +104,27 @@ class Command(BaseCommand):
self.stdout.write(f" before: {before}")
self.stdout.write(f" after: {after}")
+ def _project_quota(self, opts: dict[str, Any]) -> None:
+ if not settings.AI_GATEWAY_REDIS_URL:
+ raise CommandError("project-quota needs AI_GATEWAY_REDIS_URL; quota projection is off")
+ if opts.get("all"):
+ if opts.get("team"):
+ raise CommandError("project-quota takes a team or --all, not both")
+ counts = reconcile_quota_projection()
+ self.stdout.write(self.style.SUCCESS(f"quota projection reconciled: {counts}"))
+ return
+ if not opts.get("team"):
+ raise CommandError("project-quota needs a team id or api_token, or --all")
+ team = _resolve_team(opts["team"])
+ written = project_team_quota(team)
+ if written is None:
+ raise CommandError(f"team {team.id} ({team.api_token}): project-quota failed; see the captured error")
+ verb = "written" if written else "cleared"
+ self.stdout.write(self.style.SUCCESS(f"team {team.id} ({team.api_token}): project-quota {verb}"))
+ self.stdout.write(f" key: {team_llm_gateway_quota_hypercache.get_cache_key(team)}")
+ self.stdout.write(f" blob: {get_team_quota_blob(team)}")
+ self.stdout.write(f" ttl_seconds: {quota_blob_ttl_remaining(team)}")
+
def _resolve_team(arg: str) -> Team:
# Bare integers resolve as id; anything else as api_token (no phc_ prefix
@@ -161,3 +201,9 @@ def _print_status(stdout: Any, team: Team) -> None:
stdout.write(f" enabled_at: {team.llm_gateway_enabled_at}")
stdout.write(f" revoked_at: {team.llm_gateway_revoked_at}")
stdout.write(f" overspend_allowance_usd: {team.llm_gateway_overspend_allowance_usd}")
+ from ee.billing.quota_limiting import get_team_limited_until # noqa: PLC0415
+
+ limited = get_team_limited_until(team.api_token, AI_GATEWAY_QUOTA_BUCKETS)
+ for bucket in AI_GATEWAY_QUOTA_BUCKETS:
+ stdout.write(f" {bucket}: {'limited until ' + str(limited[bucket]) if bucket in limited else 'open'}")
+ stdout.write(f" quota_blob: {get_team_quota_blob(team)}")
diff --git a/posthog/management/commands/test/test_llm_gateway_team.py b/posthog/management/commands/test/test_llm_gateway_team.py
index 868432373c4e..6c8b816edf8c 100644
--- a/posthog/management/commands/test/test_llm_gateway_team.py
+++ b/posthog/management/commands/test/test_llm_gateway_team.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
+from django.test import override_settings
from parameterized import parameterized
@@ -159,3 +160,66 @@ class TestLLMGatewayTeamCommand(BaseTest):
self.assertEqual(self.team.llm_gateway_enabled_at, before_enabled)
self.assertEqual(self.team.llm_gateway_revoked_at, before_revoked)
self.assertIn("refresh ok", out)
+
+
+@override_settings(AI_GATEWAY_REDIS_URL="redis://localhost:6379/15")
+class TestLLMGatewayTeamProjectQuota(BaseTest):
+ def _run(self, *args: str) -> str:
+ out = StringIO()
+ call_command("llm_gateway_team", *args, stdout=out)
+ return out.getvalue()
+
+ @patch("posthog.management.commands.llm_gateway_team.project_team_quota", return_value=True)
+ @patch("posthog.management.commands.llm_gateway_team.get_team_quota_blob", return_value={"team_id": 1})
+ @patch("posthog.management.commands.llm_gateway_team.quota_blob_ttl_remaining", return_value=120)
+ def test_project_quota_writes_and_prints_the_key(self, _ttl, _blob, project) -> None:
+ out = self._run("project-quota", str(self.team.id))
+ project.assert_called_once()
+ self.assertEqual(project.call_args.args[0].id, self.team.id)
+ self.assertIn("project-quota written", out)
+ self.assertIn(f"cache/teams/{self.team.id}/team_metadata/llm_gateway_quota.json", out)
+ self.assertIn("ttl_seconds: 120", out)
+
+ @patch("posthog.management.commands.llm_gateway_team.project_team_quota", return_value=False)
+ @patch("posthog.management.commands.llm_gateway_team.get_team_quota_blob", return_value=None)
+ @patch("posthog.management.commands.llm_gateway_team.quota_blob_ttl_remaining", return_value=None)
+ def test_project_quota_reports_a_cleared_team(self, _ttl, _blob, _project) -> None:
+ out = self._run("project-quota", self.team.api_token)
+ self.assertIn("project-quota cleared", out)
+
+ @patch(
+ "posthog.management.commands.llm_gateway_team.reconcile_quota_projection",
+ return_value={"candidates": 3, "written": 2, "cleared": 0, "failed": 1},
+ )
+ def test_project_quota_all_reconciles(self, reconcile) -> None:
+ out = self._run("project-quota", "--all")
+ reconcile.assert_called_once()
+ self.assertIn("'written': 2", out)
+ self.assertIn("'failed': 1", out)
+
+ @patch("posthog.management.commands.llm_gateway_team.project_team_quota", return_value=None)
+ def test_project_quota_failure_raises(self, _project) -> None:
+ with self.assertRaisesMessage(CommandError, "project-quota failed"):
+ self._run("project-quota", str(self.team.id))
+
+ @parameterized.expand([("team",), ("all",)])
+ @patch("posthog.management.commands.llm_gateway_team.reconcile_quota_projection")
+ @patch("posthog.management.commands.llm_gateway_team.project_team_quota")
+ def test_project_quota_refuses_without_gateway_redis(self, target, project, reconcile) -> None:
+ args = ("--all",) if target == "all" else (str(self.team.id),)
+ with override_settings(AI_GATEWAY_REDIS_URL=""), self.assertRaisesMessage(CommandError, "AI_GATEWAY_REDIS_URL"):
+ self._run("project-quota", *args)
+ project.assert_not_called()
+ reconcile.assert_not_called()
+
+ def test_project_quota_needs_a_team_or_all(self) -> None:
+ with self.assertRaises(CommandError):
+ self._run("project-quota")
+ with self.assertRaises(CommandError):
+ self._run("project-quota", str(self.team.id), "--all")
+
+ def test_status_prints_the_bucket_state(self) -> None:
+ out = self._run("status", str(self.team.id))
+ self.assertIn("ai_credits: open", out)
+ self.assertIn("posthog_code_credits: open", out)
+ self.assertIn("quota_blob: None", out)
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 2a490357cb9b..1b0b530fb0cc 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -518,6 +518,7 @@ class Organization(ModelActivityMixin, UUIDTModel):
if resource == QuotaResource.RECORDINGS:
dispatch_recordings_remote_config_sync(team_id for team_id, _ in team_rows)
+ self._project_llm_gateway_quota_if_ai(resource)
else:
raise RuntimeError("Cannot limit without having a billing period")
@@ -548,6 +549,13 @@ class Organization(ModelActivityMixin, UUIDTModel):
if resource == QuotaResource.RECORDINGS:
dispatch_recordings_remote_config_sync(team_id for team_id, _ in team_rows)
+ self._project_llm_gateway_quota_if_ai(resource)
+
+ def _project_llm_gateway_quota_if_ai(self, resource: "QuotaResource") -> None:
+ from ee.billing.quota_limiting import QuotaResource, _project_llm_gateway_quota_for_org
+
+ if resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ _project_llm_gateway_quota_for_org(self)
def get_limited_products(self) -> dict[str, dict[str, Any]]:
"""
@@ -705,7 +713,18 @@ def invalidate_llm_gateway_quota_cache_on_active_state_change(sender, instance:
team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))
invalidate_llm_gateway_quota_cache(team_ids)
+ def _project_gateway_quota():
+ from posthog.tasks.team_llm_gateway_quota import project_org_llm_gateway_quota_task
+
+ try:
+ project_org_llm_gateway_quota_task.delay(str(organization_id))
+ except Exception:
+ # The reconcile re-derives a deactivated org's blobs; never fail the org save.
+ logger.warning("llm_gateway_quota_projection_enqueue_failed", organization_id=str(organization_id))
+
transaction.on_commit(_invalidate_cache)
+ if settings.AI_GATEWAY_REDIS_URL:
+ transaction.on_commit(_project_gateway_quota)
class OrganizationMembership(ModelActivityMixin, UUIDTModel):
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 30addd8ea1ce..fadffe04b3aa 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -94,10 +94,21 @@ SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEW
# entry beats the team override and the default: run cost tracks the kind of work, and
# implementation runs regularly outspend every other stage. Each interactive cap and the
# workflows cap clear their observed ceiling with room for the holds, because nothing
-# retries behind a cap that binds mid-run. Suggestion runs stay on the default.
+# retries behind a cap that binds mid-run. Suggestion runs stay on the default. A PostHog
+# Desktop cloud run has no duration cap, so its cap only bounds a runaway run.
+SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_DEFAULTS: dict[str, str] = {
+ "signals_implementation": "20",
+ "signals_inbox": "75",
+ "signals_chat": "30",
+ "slack_app": "75",
+ "workflows": "75",
+ "posthog_ai": "75",
+ "posthog_code": "500",
+}
+# A JSON object merged onto the defaults per product. Malformed JSON is captured at mint and
+# leaves the defaults in force.
SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES: str = get_from_env(
- "SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES",
- '{"signals_implementation": "20", "signals_inbox": "75", "signals_chat": "30", "slack_app": "75", "workflows": "75", "posthog_ai": "75"}',
+ "SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES", ""
)
SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS: int = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS", 0, type_cast=int)
SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=True)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index a628277c7bf5..13e53b1fa341 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1378,6 +1378,24 @@ except ValueError:
WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM = {}
WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM_INVALID = True
+# PostHog Desktop on the Go ai-gateway: the URL is the ai-gateway host because gateway.* cannot
+# validate a phe_. A dedicated relay-team phs_ keeps the mint ceiling to desktop tokens. Unset
+# refuses as `unconfigured`, which keeps the app on the legacy gateway.
+DESKTOP_GATEWAY_URL = get_from_env("DESKTOP_GATEWAY_URL", "")
+DESKTOP_GATEWAY_MINT_KEY = get_from_env("DESKTOP_GATEWAY_MINT_KEY", "")
+DESKTOP_GATEWAY_TOKEN_CAP_USD = get_from_env("DESKTOP_GATEWAY_TOKEN_CAP_USD", "200")
+# Per-team cap overrides as a JSON object of team id to dollars, e.g. {"2": "500"}.
+DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES = get_from_env("DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES", "")
+# A plan, access or membership change outlives a token by at most this long. All mints share the
+# gateway's relay-key mint ceiling, so a shorter TTL supports fewer concurrent sessions; past it the
+# gateway answers 429 and the app stays on the legacy gateway.
+DESKTOP_GATEWAY_TOKEN_TTL_SECONDS = get_from_env("DESKTOP_GATEWAY_TOKEN_TTL_SECONDS", 300, type_cast=int)
+# Org-targeted; gates the desktop mint and the sandbox worker's posthog_code mint alike.
+DESKTOP_GATEWAY_ROLLOUT_FLAG = get_from_env("DESKTOP_GATEWAY_ROLLOUT_FLAG", "posthog-desktop-ai-gateway")
+# Per-user mint ceiling because OAuth callers skip DRF's default throttles. At the default TTL each
+# open project on each device mints about 13 times an hour.
+DESKTOP_GATEWAY_MINTS_PER_HOUR = get_from_env("DESKTOP_GATEWAY_MINTS_PER_HOUR", 120, type_cast=int)
+
# Exact MCP endpoints that operators explicitly allow the MCP Store to reach even
# when normal SSRF validation rejects their private/internal address. This is an
# internal dogfooding escape hatch, not a hostname or CIDR allowlist: callers must
diff --git a/posthog/storage/team_llm_gateway_quota_cache.py b/posthog/storage/team_llm_gateway_quota_cache.py
new file mode 100644
index 000000000000..c46a3f4cab5a
--- /dev/null
+++ b/posthog/storage/team_llm_gateway_quota_cache.py
@@ -0,0 +1,380 @@
+"""
+Per-team quota blob that the Go ai-gateway's credit-bucket gate reads.
+
+Only a team limited on an AI credit bucket or in a deactivated org has a blob. The gateway reads
+absence as open, so lifting a limit deletes the key. Keyed by team id because the gateway knows
+the billed team only as an id.
+"""
+
+import os
+import json
+import time
+from collections.abc import Iterable, Mapping
+from datetime import UTC, datetime, timedelta
+from itertools import batched
+from typing import Any, NamedTuple
+
+from django.conf import settings
+from django.db.models import Q, QuerySet
+from django.db.models.functions import Coalesce
+
+import structlog
+
+from posthog.caching.ai_gateway_redis_cache import AI_GATEWAY_DEDICATED_CACHE_ALIAS
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.redis import get_client
+from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType
+
+logger = structlog.get_logger(__name__)
+
+# Strings so this module does not import the billing package at load time; a test pins them to QuotaResource.
+AI_CREDITS_BUCKET = "ai_credits"
+POSTHOG_CODE_CREDITS_BUCKET = "posthog_code_credits"
+AI_GATEWAY_QUOTA_BUCKETS: tuple[str, ...] = (AI_CREDITS_BUCKET, POSTHOG_CODE_CREDITS_BUCKET)
+
+LLM_GATEWAY_QUOTA_VERSION = 1
+
+# Margin past the limit's end so the blob outlives the zset score it mirrors.
+LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS = int(os.environ.get("LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS", "300"))
+# A deactivated org has no period end, so the reconcile re-stamps its blobs.
+LLM_GATEWAY_QUOTA_DEACTIVATED_TTL = int(os.environ.get("LLM_GATEWAY_QUOTA_DEACTIVATED_TTL", str(30 * 24 * 60 * 60)))
+
+LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET = "llm_gateway_quota_cache_expiry"
+LLM_GATEWAY_QUOTA_RESTAMP_WINDOW_SECONDS = 7 * 24 * 60 * 60
+_MAX_PROJECTION_WRITES = 3
+_BATCH_SIZE = 500
+
+
+def _never_load(team_key: KeyType) -> dict[str, Any] | HyperCacheStoreMissing:
+ # Write-only from Django, but HyperCache requires a loader. The gateway reads a miss sentinel as open.
+ return HyperCacheStoreMissing()
+
+
+team_llm_gateway_quota_hypercache = HyperCache(
+ namespace="team_metadata",
+ value="llm_gateway_quota.json",
+ token_based=False,
+ load_fn=_never_load,
+ cache_ttl=LLM_GATEWAY_QUOTA_DEACTIVATED_TTL,
+ cache_miss_ttl=60 * 60 * 24,
+ cache_alias=(AI_GATEWAY_DEDICATED_CACHE_ALIAS if AI_GATEWAY_DEDICATED_CACHE_ALIAS in settings.CACHES else None),
+ s3_enabled=False,
+ expiry_sorted_set_key=LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET,
+)
+
+
+def _iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=UTC).isoformat()
+
+
+def build_quota_blob(
+ team_id: int, limited_until: Mapping[str, float], org_active: bool, now: datetime
+) -> dict[str, Any] | None:
+ now_ts = now.timestamp()
+ buckets: dict[str, dict[str, Any]] = {}
+ if not org_active:
+ for bucket in AI_GATEWAY_QUOTA_BUCKETS:
+ buckets[bucket] = {"limited": True, "limited_until": None}
+ else:
+ for bucket in AI_GATEWAY_QUOTA_BUCKETS:
+ until = limited_until.get(bucket)
+ if until is not None and until >= now_ts:
+ buckets[bucket] = {"limited": True, "limited_until": _iso(until)}
+ if not buckets:
+ return None
+ return {
+ "team_id": team_id,
+ "version": LLM_GATEWAY_QUOTA_VERSION,
+ "buckets": buckets,
+ "org_deactivated": not org_active,
+ "projected_at": now.isoformat(),
+ }
+
+
+def quota_blob_ttl(blob: Mapping[str, Any], now: datetime) -> int:
+ if blob.get("org_deactivated"):
+ return LLM_GATEWAY_QUOTA_DEACTIVATED_TTL
+ latest = 0.0
+ for state in blob["buckets"].values():
+ until = state.get("limited_until")
+ if until:
+ latest = max(latest, datetime.fromisoformat(until).timestamp())
+ return max(1, int(latest - now.timestamp()) + LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS)
+
+
+def _enabled() -> bool:
+ return bool(settings.AI_GATEWAY_REDIS_URL)
+
+
+def deactivated_teams_needing_a_blob() -> QuerySet[Team]:
+ """Teams of deactivated orgs that can still spend at the gateway: tokens minted within the
+ deactivated window are live, or the team has a standing gateway credential."""
+ from posthog.models.project_secret_api_key import ProjectSecretAPIKey # noqa: PLC0415
+ from posthog.storage.gateway_credential_cache import GATEWAY_CREDENTIAL_REQUIRED_SCOPE # noqa: PLC0415
+
+ recent = datetime.now(tz=UTC) - timedelta(seconds=LLM_GATEWAY_QUOTA_DEACTIVATED_TTL)
+ # A secret key bills its project root, so the root is the team that needs the blob.
+ key_roots = (
+ ProjectSecretAPIKey.objects.filter(scopes__contains=[GATEWAY_CREDENTIAL_REQUIRED_SCOPE])
+ .annotate(root_team_id=Coalesce("team__parent_team_id", "team_id"))
+ .values("root_team_id")
+ )
+ return (
+ Team.objects.filter(organization__is_active=False)
+ .filter(
+ Q(organization__updated_at__gte=recent)
+ | Q(llm_gateway_enabled_at__isnull=False, llm_gateway_revoked_at__isnull=True)
+ | Q(id__in=key_roots)
+ | Q(organization__oauth_applications__isnull=False)
+ )
+ .distinct()
+ )
+
+
+def _derive_blobs(teams: list[Team], now: datetime) -> dict[int, dict[str, Any] | None]:
+ from ee.billing.quota_limiting import get_teams_limited_until # noqa: PLC0415
+
+ # A NULL is_active counts as active.
+ active_by_org = dict(
+ Organization.objects.filter(id__in={team.organization_id for team in teams}).values_list("id", "is_active")
+ )
+ active = {team.id: active_by_org.get(team.organization_id) is not False for team in teams}
+ inactive_ids = [team.id for team in teams if not active[team.id]]
+ reachable = (
+ set(deactivated_teams_needing_a_blob().filter(id__in=inactive_ids).values_list("id", flat=True))
+ if inactive_ids
+ else set()
+ )
+ limited = get_teams_limited_until([team.api_token for team in teams if active[team.id]], AI_GATEWAY_QUOTA_BUCKETS)
+ blobs: dict[int, dict[str, Any] | None] = {}
+ for team in teams:
+ if active[team.id]:
+ blobs[team.id] = build_quota_blob(team.id, limited[team.api_token], True, now)
+ else:
+ blobs[team.id] = build_quota_blob(team.id, {}, False, now) if team.id in reachable else None
+ return blobs
+
+
+@frozen
+class _BlobState:
+ org_deactivated: Any
+ buckets: Any
+
+
+def _blob_state(blob: Mapping[str, Any] | None) -> _BlobState | None:
+ return None if blob is None else _BlobState(org_deactivated=blob["org_deactivated"], buckets=blob["buckets"])
+
+
+def _write_blob(team: Team, blob: dict[str, Any] | None, now: datetime) -> None:
+ if blob is None:
+ team_llm_gateway_quota_hypercache.delete_cache_entry(team, kinds=["redis"])
+ else:
+ team_llm_gateway_quota_hypercache.set_cache_value_redis_only(
+ team, blob, ttl=quota_blob_ttl(blob, now), track_expiry=True
+ )
+
+
+def _capture_failure(message: str, error: Exception, **fields: Any) -> None:
+ logger.warning(message, error_type=type(error).__name__, error=str(error), **fields)
+ capture_exception(error)
+
+
+def _derive_or_capture(teams: list[Team], now: datetime) -> dict[int, dict[str, Any] | None]:
+ """Empty when the read fails. No per-team input fails alone, so a failure means a store is
+ down: capture it once and leave the batch to the reconcile."""
+ if not teams:
+ return {}
+ try:
+ return _derive_blobs(teams, now)
+ except Exception as e:
+ _capture_failure("llm_gateway_quota: projection read failed", e, teams=len(teams))
+ return {}
+
+
+class _Projected(NamedTuple):
+ written: int
+ cleared: int
+
+
+def _project_batch(teams: list[Team]) -> _Projected:
+ """Writes each blob, then re-reads and rewrites what moved. Writers race, and each re-read
+ follows every earlier write, so the last write carries current state. Failures are captured
+ for the reconcile, never raised into billing. Counts the blobs left written and the clears
+ that succeeded."""
+ by_id = {team.id: team for team in teams}
+ written: dict[int, dict[str, Any] | None] = {}
+ to_write = _derive_or_capture(teams, datetime.now(tz=UTC))
+ for _ in range(_MAX_PROJECTION_WRITES):
+ now = datetime.now(tz=UTC)
+ for team_id, blob in to_write.items():
+ try:
+ _write_blob(by_id[team_id], blob, now)
+ written[team_id] = blob
+ except Exception as e:
+ _capture_failure("llm_gateway_quota: projection write failed", e, team_id=team_id)
+ written.pop(team_id, None)
+ current = _derive_or_capture([by_id[team_id] for team_id in written], datetime.now(tz=UTC))
+ to_write = {
+ team_id: current[team_id]
+ for team_id in written
+ if team_id in current and _blob_state(current[team_id]) != _blob_state(written[team_id])
+ }
+ if not to_write:
+ break
+ else:
+ # State kept moving; the reconcile re-projects these teams within a tick.
+ logger.warning("llm_gateway_quota: projection did not settle", team_ids=sorted(to_write))
+ blobs = sum(1 for blob in written.values() if blob is not None)
+ return _Projected(blobs, len(written) - blobs)
+
+
+def _project_in_batches(queryset: QuerySet[Team]) -> _Projected:
+ written = cleared = 0
+ for batch in batched(queryset.iterator(chunk_size=_BATCH_SIZE), _BATCH_SIZE, strict=False):
+ projected = _project_batch(list(batch))
+ written += projected.written
+ cleared += projected.cleared
+ return _Projected(written, cleared)
+
+
+def _project_teams(queryset: QuerySet[Team]) -> _Projected:
+ return _project_in_batches(queryset.only("id", "api_token", "organization_id"))
+
+
+def project_team_quota(team: Team) -> bool | None:
+ """True when a blob is written, False when cleared, None when the projection failed or is off."""
+ if not _enabled():
+ return None
+ projected = _project_batch([team])
+ return True if projected.written else False if projected.cleared else None
+
+
+def clear_team_quota(team: Team | int) -> None:
+ if not _enabled():
+ return
+ try:
+ team_llm_gateway_quota_hypercache.delete_cache_entry(team, kinds=["redis"])
+ except Exception as e:
+ team_id = team.id if isinstance(team, Team) else team
+ logger.warning("llm_gateway_quota: clear failed", team_id=team_id, error=str(e))
+ capture_exception(e)
+
+
+def project_org_quota(organization: Organization) -> int:
+ """Includes child environments so an obo naming either the project or an environment resolves."""
+ if not _enabled():
+ return 0
+ return _project_teams(organization.teams.all()).written
+
+
+def project_teams_quota_by_token(tokens: Iterable[str]) -> int:
+ if not _enabled():
+ return 0
+ token_list = [t for t in set(tokens) if t]
+ if not token_list:
+ return 0
+ return _project_teams(Team.objects.filter(api_token__in=token_list)).written
+
+
+def projected_team_ids(expiring_before: float | None = None) -> set[int]:
+ if not _enabled():
+ return set()
+ client = get_client(team_llm_gateway_quota_hypercache.redis_url)
+ if expiring_before is None:
+ members = client.zrange(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET, 0, -1)
+ else:
+ members = client.zrangebyscore(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET, "-inf", f"({expiring_before}")
+ out: set[int] = set()
+ for member in members:
+ raw = member.decode("utf-8") if isinstance(member, bytes) else str(member)
+ try:
+ out.add(int(raw))
+ except ValueError:
+ continue
+ return out
+
+
+def _untrack(team_ids: set[int], *, expired_before: float) -> None:
+ if not team_ids:
+ return
+ client = get_client(team_llm_gateway_quota_hypercache.redis_url)
+ expired = projected_team_ids(expiring_before=expired_before) & team_ids
+ if expired:
+ client.zrem(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET, *(str(team_id) for team_id in expired))
+
+
+def _missing_blobs(team_ids: set[int]) -> set[int]:
+ missing: set[int] = set()
+ ordered = sorted(team_ids)
+ client = team_llm_gateway_quota_hypercache.cache_client
+ for start in range(0, len(ordered), 500):
+ keys = {
+ team_llm_gateway_quota_hypercache.get_cache_key(team_id): team_id
+ for team_id in ordered[start : start + 500]
+ }
+ present = client.get_many(list(keys))
+ missing.update(team_id for key, team_id in keys.items() if key not in present)
+ return missing
+
+
+def reconcile_quota_projection() -> dict[str, int]:
+ """Re-projects every team limited on an AI bucket or in a reachable deactivated org, and every
+ team with a blob, which deletes a stray one."""
+ if not _enabled():
+ return {"candidates": 0, "written": 0, "cleared": 0, "failed": 0}
+ from ee.billing.quota_limiting import ( # noqa: PLC0415
+ QuotaLimitingCaches,
+ QuotaResource,
+ list_team_attributes_in_zset,
+ )
+
+ tokens: set[str] = set()
+ for bucket in AI_GATEWAY_QUOTA_BUCKETS:
+ tokens.update(list_team_attributes_in_zset(QuotaResource(bucket), QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY))
+ now_ts = time.time()
+ have = projected_team_ids()
+ expiring = projected_team_ids(expiring_before=now_ts + LLM_GATEWAY_QUOTA_RESTAMP_WINDOW_SECONDS)
+ have_active = dict(Team.objects.filter(id__in=have).values_list("id", "organization__is_active"))
+ # A deleted team is never re-projected; drop its tracking once its blob has expired.
+ _untrack(have - set(have_active), expired_before=now_ts)
+ deactivated_have = {team_id for team_id, active in have_active.items() if active is False}
+ # Only deactivated teams that can still spend keep a blob. A present one is left until its
+ # window, so the tick does not rewrite every deactivated team; one that can no longer spend
+ # is re-projected once, which deletes it.
+ reachable = set(deactivated_teams_needing_a_blob().values_list("id", flat=True))
+ ids = (
+ expiring
+ | (set(have_active) - deactivated_have)
+ | (deactivated_have - reachable)
+ | _missing_blobs(reachable - expiring)
+ )
+ candidates = Team.objects.filter(Q(api_token__in=tokens) | Q(id__in=ids))
+ total = candidates.count()
+ projected = _project_teams(candidates)
+ failed = max(0, total - projected.written - projected.cleared)
+ return {"candidates": total, "written": projected.written, "cleared": projected.cleared, "failed": failed}
+
+
+def get_team_quota_blob(team: Team | int) -> dict[str, Any] | None:
+ """Redis-only read that never fills the cache. The cache holds the JSON text the gateway decodes."""
+ value = team_llm_gateway_quota_hypercache.cache_client.get(team_llm_gateway_quota_hypercache.get_cache_key(team))
+ if isinstance(value, dict):
+ return value
+ if isinstance(value, str | bytes):
+ try:
+ decoded = json.loads(value)
+ except ValueError:
+ return None
+ return decoded if isinstance(decoded, dict) else None
+ return None
+
+
+def quota_blob_ttl_remaining(team: Team | int) -> int | None:
+ cache = team_llm_gateway_quota_hypercache.cache_client
+ ttl = get_client(team_llm_gateway_quota_hypercache.redis_url).ttl(
+ cache.make_key(team_llm_gateway_quota_hypercache.get_cache_key(team))
+ )
+ return None if ttl is None or ttl < 0 else int(ttl)
diff --git a/posthog/storage/test/test_team_llm_gateway_quota_cache.py b/posthog/storage/test/test_team_llm_gateway_quota_cache.py
new file mode 100644
index 000000000000..28b5db9db0e8
--- /dev/null
+++ b/posthog/storage/test/test_team_llm_gateway_quota_cache.py
@@ -0,0 +1,620 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import connection
+from django.test import SimpleTestCase
+from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.oauth import OAuthApplication
+from posthog.models.organization import Organization
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.team.team import Team
+from posthog.redis import get_client
+from posthog.storage.team_llm_gateway_quota_cache import (
+ AI_CREDITS_BUCKET,
+ AI_GATEWAY_QUOTA_BUCKETS,
+ LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET,
+ LLM_GATEWAY_QUOTA_DEACTIVATED_TTL,
+ LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS,
+ POSTHOG_CODE_CREDITS_BUCKET,
+ build_quota_blob,
+ clear_team_quota,
+ get_team_quota_blob,
+ project_org_quota,
+ project_team_quota,
+ project_teams_quota_by_token,
+ projected_team_ids,
+ quota_blob_ttl,
+ quota_blob_ttl_remaining,
+ reconcile_quota_projection,
+ team_llm_gateway_quota_hypercache as hypercache,
+)
+
+from ee.billing.quota_limiting import (
+ QuotaLimitingCaches,
+ QuotaResource,
+ add_limited_team_tokens,
+ get_team_limited_until,
+ remove_limited_team_tokens,
+)
+
+_GATEWAY_REDIS_URL = "redis://localhost:6379/15"
+_NOW = datetime(2026, 9, 22, 12, 0, 0, tzinfo=UTC)
+
+
+def _limit(team: Team, resource: QuotaResource, until: float) -> None:
+ add_limited_team_tokens(resource, {team.api_token: int(until)}, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+
+def _unlimit(team: Team, resource: QuotaResource) -> None:
+ remove_limited_team_tokens(resource, [team.api_token], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+
+class QuotaProjectionTestMixin(BaseTest):
+ def setUp(self):
+ super().setUp()
+ hypercache.cache_client.clear()
+ get_client(hypercache.redis_url).delete(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET)
+ for resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ _unlimit(self.team, resource)
+
+ def tearDown(self):
+ for resource in (QuotaResource.AI_CREDITS, QuotaResource.POSTHOG_CODE_CREDITS):
+ _unlimit(self.team, resource)
+ super().tearDown()
+
+
+class TestQuotaBlob(SimpleTestCase):
+ def test_bucket_names_are_the_quota_resources(self):
+ self.assertEqual(AI_CREDITS_BUCKET, QuotaResource.AI_CREDITS.value)
+ self.assertEqual(POSTHOG_CODE_CREDITS_BUCKET, QuotaResource.POSTHOG_CODE_CREDITS.value)
+ self.assertEqual(set(AI_GATEWAY_QUOTA_BUCKETS), {"ai_credits", "posthog_code_credits"})
+
+ def test_unlimited_active_team_has_no_blob(self):
+ self.assertIsNone(build_quota_blob(42, {}, True, _NOW))
+
+ def test_limited_bucket_only_appears(self):
+ until = (_NOW + timedelta(days=9)).timestamp()
+ blob = build_quota_blob(42, {"posthog_code_credits": until}, True, _NOW)
+ self.assertEqual(
+ blob,
+ {
+ "team_id": 42,
+ "version": 1,
+ "buckets": {"posthog_code_credits": {"limited": True, "limited_until": "2026-10-01T12:00:00+00:00"}},
+ "org_deactivated": False,
+ "projected_at": "2026-09-22T12:00:00+00:00",
+ },
+ )
+
+ def test_lapsed_score_is_not_a_limit(self):
+ past = (_NOW - timedelta(seconds=1)).timestamp()
+ self.assertIsNone(build_quota_blob(42, {"ai_credits": past}, True, _NOW))
+
+ def test_deactivated_org_limits_every_bucket_without_an_end(self):
+ blob = build_quota_blob(42, {}, False, _NOW)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+ self.assertEqual(
+ blob["buckets"],
+ {
+ "ai_credits": {"limited": True, "limited_until": None},
+ "posthog_code_credits": {"limited": True, "limited_until": None},
+ },
+ )
+
+ def test_ttl_runs_past_the_latest_limit_end(self):
+ soon = (_NOW + timedelta(hours=1)).timestamp()
+ later = (_NOW + timedelta(days=2)).timestamp()
+ blob = build_quota_blob(42, {"ai_credits": soon, "posthog_code_credits": later}, True, _NOW)
+ assert blob is not None
+ self.assertEqual(quota_blob_ttl(blob, _NOW), 2 * 24 * 3600 + LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS)
+
+ def test_ttl_for_a_deactivated_org_is_the_fixed_window(self):
+ blob = build_quota_blob(42, {}, False, _NOW)
+ assert blob is not None
+ self.assertEqual(quota_blob_ttl(blob, _NOW), LLM_GATEWAY_QUOTA_DEACTIVATED_TTL)
+ self.assertEqual(LLM_GATEWAY_QUOTA_DEACTIVATED_TTL, 30 * 24 * 3600)
+
+
+@patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+class TestProjectTeamQuota(QuotaProjectionTestMixin):
+ def _enable(self, mock_settings) -> None:
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+
+ def test_limited_team_is_written_under_the_team_id_key(self, mock_settings):
+ self._enable(mock_settings)
+ until = timezone.now() + timedelta(days=3)
+ _limit(self.team, QuotaResource.AI_CREDITS, until.timestamp())
+
+ self.assertTrue(project_team_quota(self.team))
+
+ self.assertEqual(
+ hypercache.get_cache_key(self.team), f"cache/teams/{self.team.id}/team_metadata/llm_gateway_quota.json"
+ )
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertEqual(blob["team_id"], self.team.id)
+ self.assertEqual(blob["org_deactivated"], False)
+ self.assertEqual(set(blob["buckets"]), {"ai_credits"})
+ self.assertTrue(blob["buckets"]["ai_credits"]["limited"])
+ self.assertIn(self.team.id, projected_team_ids())
+
+ def test_ttl_is_the_limit_end_plus_margin(self, mock_settings):
+ self._enable(mock_settings)
+ until = timezone.now() + timedelta(days=3)
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, until.timestamp())
+ with patch.object(hypercache, "set_cache_value_redis_only", wraps=hypercache.set_cache_value_redis_only) as w:
+ project_team_quota(self.team)
+ ttl = w.call_args.kwargs["ttl"]
+ self.assertAlmostEqual(ttl, 3 * 24 * 3600 + LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS, delta=5)
+ self.assertTrue(w.call_args.kwargs["track_expiry"])
+
+ def test_ttl_remaining_reads_the_key_the_cache_writes(self, mock_settings):
+ client = get_client(hypercache.redis_url)
+ key = hypercache.cache_client.make_key(hypercache.get_cache_key(self.team))
+ client.delete(key)
+ self.assertIsNone(quota_blob_ttl_remaining(self.team))
+ client.set(key, b"blob", ex=300)
+ try:
+ remaining = quota_blob_ttl_remaining(self.team)
+ finally:
+ client.delete(key)
+ assert remaining is not None
+ self.assertAlmostEqual(remaining, 300, delta=5)
+
+ def test_both_buckets_take_the_latest_end(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(hours=1)).timestamp())
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, (timezone.now() + timedelta(days=5)).timestamp())
+ with patch.object(hypercache, "set_cache_value_redis_only", wraps=hypercache.set_cache_value_redis_only) as w:
+ project_team_quota(self.team)
+ self.assertAlmostEqual(w.call_args.kwargs["ttl"], 5 * 24 * 3600 + LLM_GATEWAY_QUOTA_TTL_MARGIN_SECONDS, delta=5)
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertEqual(set(blob["buckets"]), {"ai_credits", "posthog_code_credits"})
+
+ def test_lifting_the_limit_deletes_the_blob(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ project_team_quota(self.team)
+ self.assertIsNotNone(get_team_quota_blob(self.team))
+
+ _unlimit(self.team, QuotaResource.AI_CREDITS)
+ self.assertIs(project_team_quota(self.team), False)
+
+ # A plain delete, never a miss sentinel.
+ self.assertIsNone(hypercache.cache_client.get(hypercache.get_cache_key(self.team)))
+ self.assertNotIn(self.team.id, projected_team_ids())
+
+ def test_expired_score_is_ignored(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() - timedelta(seconds=5)).timestamp())
+ self.assertIs(project_team_quota(self.team), False)
+ self.assertIsNone(get_team_quota_blob(self.team))
+
+ def test_deactivated_org_projects_every_team_with_the_fixed_ttl(self, mock_settings):
+ self._enable(mock_settings)
+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)
+ self.organization.is_active = False
+ self.organization.save()
+ with patch.object(hypercache, "set_cache_value_redis_only", wraps=hypercache.set_cache_value_redis_only) as w:
+ written = project_org_quota(self.organization)
+ self.assertEqual(written, 2)
+ self.assertEqual({c.kwargs["ttl"] for c in w.call_args_list}, {LLM_GATEWAY_QUOTA_DEACTIVATED_TTL})
+ for team in (self.team, child):
+ blob = get_team_quota_blob(team)
+ assert blob is not None, team.id
+ self.assertTrue(blob["org_deactivated"])
+ self.assertEqual(blob["buckets"]["posthog_code_credits"], {"limited": True, "limited_until": None})
+
+ def test_child_environment_is_projected_under_its_own_id(self, mock_settings):
+ self._enable(mock_settings)
+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)
+ _limit(child, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=1)).timestamp())
+ try:
+ self.assertEqual(project_teams_quota_by_token([child.api_token]), 1)
+ blob = get_team_quota_blob(child)
+ assert blob is not None
+ self.assertEqual(blob["team_id"], child.id)
+ self.assertIsNone(get_team_quota_blob(self.team))
+ finally:
+ _unlimit(child, QuotaResource.AI_CREDITS)
+
+ def test_noop_without_gateway_redis_url(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = None
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ self.assertIsNone(project_team_quota(self.team))
+ self.assertIsNone(get_team_quota_blob(self.team))
+ self.assertEqual(reconcile_quota_projection(), {"candidates": 0, "written": 0, "cleared": 0, "failed": 0})
+
+ def test_redis_failure_is_captured_not_raised(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ with (
+ patch.object(hypercache, "set_cache_value_redis_only", side_effect=ConnectionError("redis down")),
+ patch("posthog.storage.team_llm_gateway_quota_cache.capture_exception") as capture,
+ ):
+ self.assertIsNone(project_team_quota(self.team))
+ capture.assert_called_once()
+
+ def test_a_writer_that_read_stale_state_rewrites_the_current_state(self, mock_settings):
+ # A writer read "limited", then the limit lifted and another writer deleted the blob before
+ # this one wrote. The re-read after its write must leave the blob deleted.
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ real_write = hypercache.set_cache_value_redis_only
+
+ def lift_then_write(*args, **kwargs):
+ _unlimit(self.team, QuotaResource.AI_CREDITS)
+ return real_write(*args, **kwargs)
+
+ with patch.object(hypercache, "set_cache_value_redis_only", side_effect=lift_then_write):
+ self.assertIs(project_team_quota(self.team), False)
+ self.assertIsNone(get_team_quota_blob(self.team))
+ self.assertNotIn(self.team.id, projected_team_ids())
+
+ def test_a_writer_that_read_open_state_rewrites_a_new_limit(self, mock_settings):
+ self._enable(mock_settings)
+ real_delete = hypercache.delete_cache_entry
+
+ def limit_then_delete(*args, **kwargs):
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ return real_delete(*args, **kwargs)
+
+ with patch.object(hypercache, "delete_cache_entry", side_effect=limit_then_delete):
+ self.assertTrue(project_team_quota(self.team))
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["buckets"]["posthog_code_credits"]["limited"])
+
+ def test_an_org_deactivated_after_the_first_read_is_rewritten(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ real_write = hypercache.set_cache_value_redis_only
+ calls = iter(range(10))
+
+ def deactivate_then_write(*args, **kwargs):
+ if next(calls) == 0:
+ Organization.objects.filter(pk=self.organization.pk).update(is_active=False)
+ return real_write(*args, **kwargs)
+
+ with patch.object(hypercache, "set_cache_value_redis_only", side_effect=deactivate_then_write):
+ self.assertTrue(project_team_quota(self.team))
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
+ def test_a_failed_re_read_leaves_the_writes_for_the_reconcile(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ from posthog.storage import team_llm_gateway_quota_cache as module
+
+ real_derive = module._derive_blobs
+ with (
+ patch.object(
+ module, "_derive_blobs", side_effect=[real_derive([self.team], timezone.now()), ConnectionError("down")]
+ ),
+ patch("posthog.storage.team_llm_gateway_quota_cache.capture_exception") as capture,
+ ):
+ self.assertTrue(project_team_quota(self.team))
+ capture.assert_called_once()
+ self.assertIsNotNone(get_team_quota_blob(self.team))
+
+ def test_a_failed_rewrite_is_captured_and_not_counted(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ real_write = hypercache.set_cache_value_redis_only
+ writes = iter(range(10))
+
+ def lift_then_fail(*args, **kwargs):
+ if next(writes) == 0:
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ return real_write(*args, **kwargs)
+ raise ConnectionError("gateway redis down")
+
+ with (
+ patch.object(hypercache, "set_cache_value_redis_only", side_effect=lift_then_fail),
+ patch("posthog.storage.team_llm_gateway_quota_cache.capture_exception") as capture,
+ ):
+ self.assertIsNone(project_team_quota(self.team))
+ capture.assert_called_once()
+
+ def test_batches_are_bounded_and_every_team_is_projected(self, mock_settings):
+ self._enable(mock_settings)
+ teams = [self.team] + [Team.objects.create(organization=self.organization, name=f"b{i}") for i in range(4)]
+ for team in teams:
+ _limit(team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=1)).timestamp())
+ from posthog.storage import team_llm_gateway_quota_cache as module
+
+ try:
+ with (
+ patch.object(module, "_BATCH_SIZE", 2),
+ patch.object(module, "_derive_blobs", wraps=module._derive_blobs) as derive,
+ ):
+ self.assertEqual(project_org_quota(self.organization), 5)
+ self.assertLessEqual(max(len(call.args[0]) for call in derive.call_args_list), 2)
+ for team in teams:
+ self.assertIsNotNone(get_team_quota_blob(team), team.id)
+ finally:
+ for team in teams[1:]:
+ _unlimit(team, QuotaResource.AI_CREDITS)
+
+ def test_state_that_never_settles_gives_up_after_three_writes(self, mock_settings):
+ self._enable(mock_settings)
+ flips = iter(range(100))
+
+ def flipping(teams, now):
+ active = next(flips) % 2 == 1
+ return {team.id: build_quota_blob(team.id, {}, active, now) for team in teams}
+
+ with (
+ patch("posthog.storage.team_llm_gateway_quota_cache._derive_blobs", side_effect=flipping),
+ patch.object(hypercache, "delete_cache_entry", wraps=hypercache.delete_cache_entry) as deletes,
+ patch.object(hypercache, "set_cache_value_redis_only", wraps=hypercache.set_cache_value_redis_only) as sets,
+ ):
+ project_team_quota(self.team)
+ self.assertEqual(deletes.call_count + sets.call_count, 3)
+
+ def test_a_writer_that_read_one_bucket_rewrites_a_second_bucket_limited_meanwhile(self, mock_settings):
+ self._enable(mock_settings)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ real_write = hypercache.set_cache_value_redis_only
+ calls = iter(range(10))
+
+ def limit_code_then_write(*args, **kwargs):
+ if next(calls) == 0:
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ return real_write(*args, **kwargs)
+
+ with patch.object(hypercache, "set_cache_value_redis_only", side_effect=limit_code_then_write):
+ self.assertTrue(project_team_quota(self.team))
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertEqual(set(blob["buckets"]), {"ai_credits", "posthog_code_credits"})
+
+ def test_org_flags_are_read_once_per_pass_not_per_team(self, mock_settings):
+ self._enable(mock_settings)
+ teams = [self.team] + [Team.objects.create(organization=self.organization, name=f"t{i}") for i in range(3)]
+ for team in teams:
+ _limit(team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=1)).timestamp())
+ try:
+ with CaptureQueriesContext(connection) as queries:
+ self.assertEqual(project_org_quota(self.organization), 4)
+ org_reads = [q["sql"] for q in queries.captured_queries if 'FROM "posthog_organization"' in q["sql"]]
+ # One read for the write, one for the re-read, for all four teams.
+ self.assertEqual(len(org_reads), 2, org_reads)
+ finally:
+ for team in teams[1:]:
+ _unlimit(team, QuotaResource.AI_CREDITS)
+
+ def test_a_failed_batch_read_is_captured_once_and_the_next_batch_still_projects(self, mock_settings):
+ self._enable(mock_settings)
+ other = Team.objects.create(organization=self.organization, name="other")
+ for team in (self.team, other):
+ _limit(team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=1)).timestamp())
+ from posthog.storage import team_llm_gateway_quota_cache as module
+
+ from ee.billing import quota_limiting
+
+ real_read = quota_limiting.get_teams_limited_until
+
+ def failing_for_first_team(tokens, resources):
+ if self.team.api_token in tokens:
+ raise ConnectionError("quota redis down")
+ return real_read(tokens, resources)
+
+ try:
+ with (
+ patch.object(module, "_BATCH_SIZE", 1),
+ patch("ee.billing.quota_limiting.get_teams_limited_until", side_effect=failing_for_first_team),
+ patch("posthog.storage.team_llm_gateway_quota_cache.capture_exception") as capture,
+ ):
+ self.assertEqual(project_teams_quota_by_token([self.team.api_token, other.api_token]), 1)
+ capture.assert_called_once()
+ self.assertIsNone(get_team_quota_blob(self.team))
+ self.assertIsNotNone(get_team_quota_blob(other))
+ finally:
+ _unlimit(other, QuotaResource.AI_CREDITS)
+
+ def test_a_failed_batch_read_is_not_retried_team_by_team(self, mock_settings):
+ self._enable(mock_settings)
+ teams = [self.team] + [Team.objects.create(organization=self.organization, name=f"f{i}") for i in range(3)]
+ from posthog.storage import team_llm_gateway_quota_cache as module
+
+ with (
+ patch.object(module, "_derive_blobs", side_effect=ConnectionError("store down")) as derive,
+ patch("posthog.storage.team_llm_gateway_quota_cache.capture_exception") as capture,
+ ):
+ self.assertEqual(project_org_quota(self.organization), 0)
+ derive.assert_called_once()
+ self.assertEqual(len(derive.call_args.args[0]), len(teams))
+ capture.assert_called_once()
+
+ def test_reachability_is_read_only_for_the_batch_teams(self, mock_settings):
+ self._enable(mock_settings)
+ self.organization.is_active = False
+ self.organization.save()
+ with CaptureQueriesContext(connection) as queries:
+ project_team_quota(self.team)
+ reach = [q["sql"] for q in queries.captured_queries if "posthog_projectsecretapikey" in q["sql"]]
+ self.assertTrue(reach)
+ for sql in reach:
+ self.assertIn(f'"posthog_team"."id" IN ({self.team.id})', sql)
+
+ def test_get_team_limited_until_reads_scores_fresh(self, mock_settings):
+ until = int((timezone.now() + timedelta(days=3)).timestamp())
+ _limit(self.team, QuotaResource.POSTHOG_CODE_CREDITS, until)
+ limited = get_team_limited_until(self.team.api_token, AI_GATEWAY_QUOTA_BUCKETS)
+ self.assertEqual(limited, {"posthog_code_credits": float(until)})
+ _unlimit(self.team, QuotaResource.POSTHOG_CODE_CREDITS)
+ self.assertEqual(get_team_limited_until(self.team.api_token, AI_GATEWAY_QUOTA_BUCKETS), {})
+
+
+@patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+class TestReconcileQuotaProjection(QuotaProjectionTestMixin):
+ def test_reconcile_writes_limited_removes_strays_and_is_idempotent(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ stray = Team.objects.create(organization=self.organization, name="stray")
+ hypercache.set_cache_value_redis_only(stray, {"team_id": stray.id, "buckets": {}}, ttl=600, track_expiry=True)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+
+ first = reconcile_quota_projection()
+ self.assertEqual(first, {"candidates": 2, "written": 1, "cleared": 1, "failed": 0})
+ self.assertIsNotNone(get_team_quota_blob(self.team))
+ self.assertIsNone(get_team_quota_blob(stray))
+ self.assertEqual(projected_team_ids(), {self.team.id})
+
+ second = reconcile_quota_projection()
+ self.assertEqual(second, {"candidates": 1, "written": 1, "cleared": 0, "failed": 0})
+ self.assertEqual(projected_team_ids(), {self.team.id})
+
+ def test_reconcile_counts_failed_writes_and_clears_apart(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ stray = Team.objects.create(organization=self.organization, name="stray")
+ hypercache.set_cache_value_redis_only(stray, {"team_id": stray.id, "buckets": {}}, ttl=600, track_expiry=True)
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+
+ with patch.object(hypercache, "set_cache_value_redis_only", side_effect=ConnectionError("redis down")):
+ counts = reconcile_quota_projection()
+ self.assertEqual(counts, {"candidates": 2, "written": 0, "cleared": 1, "failed": 1})
+
+ hypercache.set_cache_value_redis_only(stray, {"team_id": stray.id, "buckets": {}}, ttl=600, track_expiry=True)
+ with patch.object(hypercache, "delete_cache_entry", side_effect=ConnectionError("redis down")):
+ counts = reconcile_quota_projection()
+ self.assertEqual(counts, {"candidates": 2, "written": 1, "cleared": 0, "failed": 1})
+
+ def test_reconcile_restamps_a_deactivated_org_that_carries_a_blob(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ self.organization.is_active = False
+ self.organization.save()
+ project_org_quota(self.organization)
+ self.assertIn(self.team.id, projected_team_ids())
+
+ # A fresh deactivated blob is left alone; one inside the re-stamp window is rewritten.
+ self.assertEqual(reconcile_quota_projection()["candidates"], 0)
+ get_client(hypercache.redis_url).zadd(
+ "llm_gateway_quota_cache_expiry", {str(self.team.id): int(timezone.now().timestamp()) + 3600}
+ )
+ counts = reconcile_quota_projection()
+ self.assertEqual(counts["written"], 1)
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+ self.assertEqual(reconcile_quota_projection()["candidates"], 0)
+
+ def test_reconcile_rewrites_an_evicted_deactivated_blob_whose_tracking_survived(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ self.organization.is_active = False
+ self.organization.save()
+ project_org_quota(self.organization)
+ hypercache.cache_client.delete(hypercache.get_cache_key(self.team))
+ self.assertIn(self.team.id, projected_team_ids())
+ self.assertIsNone(get_team_quota_blob(self.team))
+
+ reconcile_quota_projection()
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
+ def test_a_null_active_flag_reads_as_active(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ Organization.objects.filter(pk=self.organization.pk).update(is_active=None)
+ self.organization.refresh_from_db()
+ project_org_quota(self.organization)
+ self.assertIsNone(get_team_quota_blob(self.team))
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ project_teams_quota_by_token([self.team.api_token])
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertFalse(blob["org_deactivated"])
+ self.assertEqual(set(blob["buckets"]), {"ai_credits"})
+
+ def test_reconcile_derives_a_deactivated_org_with_no_blob_from_postgres(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ Organization.objects.filter(pk=self.organization.pk).update(is_active=False)
+ self.assertNotIn(self.team.id, projected_team_ids())
+
+ reconcile_quota_projection()
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
+ def _deactivate_long_ago(self) -> None:
+ Organization.objects.filter(pk=self.organization.pk).update(
+ is_active=False, updated_at=timezone.now() - timedelta(seconds=LLM_GATEWAY_QUOTA_DEACTIVATED_TTL + 60)
+ )
+
+ def test_a_long_deactivated_org_with_no_gateway_credential_loses_its_blob(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ self.organization.is_active = False
+ self.organization.save()
+ project_org_quota(self.organization)
+ self.assertIsNotNone(get_team_quota_blob(self.team))
+ self._deactivate_long_ago()
+
+ reconcile_quota_projection()
+ self.assertIsNone(get_team_quota_blob(self.team))
+ self.assertNotIn(self.team.id, projected_team_ids())
+ self.assertEqual(reconcile_quota_projection()["candidates"], 0)
+ self.assertIsNone(get_team_quota_blob(self.team))
+
+ @parameterized.expand(["admission_enabled", "secret_key_on_child_env", "oauth_app"])
+ def test_a_long_deactivated_org_that_can_still_reach_the_gateway_keeps_its_blob(self, mock_settings, credential):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ if credential == "admission_enabled":
+ Team.objects.filter(pk=self.team.pk).update(llm_gateway_enabled_at=timezone.now())
+ elif credential == "secret_key_on_child_env":
+ child = Team.objects.create(organization=self.organization, name="child env", parent_team=self.team)
+ ProjectSecretAPIKey.objects.create(
+ team=child, label="gateway", scopes=["llm_gateway:read"], secure_value="sha256$quota-test"
+ )
+ else:
+ OAuthApplication.objects.create(
+ name="An app",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ self._deactivate_long_ago()
+
+ reconcile_quota_projection()
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
+ def test_a_revoked_admission_does_not_keep_a_long_deactivated_blob(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ Team.objects.filter(pk=self.team.pk).update(
+ llm_gateway_enabled_at=timezone.now(), llm_gateway_revoked_at=timezone.now()
+ )
+ ProjectSecretAPIKey.objects.create(
+ team=self.team, label="not gateway", scopes=["query:read"], secure_value="sha256$quota-test-2"
+ )
+ self._deactivate_long_ago()
+ reconcile_quota_projection()
+ self.assertIsNone(get_team_quota_blob(self.team))
+
+ def test_reconcile_untracks_a_deleted_team_once_its_blob_expired(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ client = get_client(hypercache.redis_url)
+ now = int(timezone.now().timestamp())
+ client.zadd(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET, {"987654321": now - 10, "987654322": now + 3600})
+ reconcile_quota_projection()
+ self.assertEqual(projected_team_ids(), {987654322})
+
+ def test_clear_removes_blob_and_tracking(self, mock_settings):
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ _limit(self.team, QuotaResource.AI_CREDITS, (timezone.now() + timedelta(days=3)).timestamp())
+ project_team_quota(self.team)
+ clear_team_quota(self.team.id)
+ self.assertIsNone(get_team_quota_blob(self.team))
+ self.assertNotIn(self.team.id, projected_team_ids())
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 3562642229ba..1775f583672f 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -70,6 +70,7 @@ from posthog.tasks.tasks import (
)
from posthog.tasks.team_event_volume import update_team_event_volumes
from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_policy_cache_entries
+from posthog.tasks.team_llm_gateway_quota import reconcile_llm_gateway_quota_projection
from posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries
from posthog.tasks.uploaded_media import sweep_abandoned_media_uploads_task
from posthog.tasks.wizard_blocklist import revoke_blocklisted_gateway_credentials
@@ -361,6 +362,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="gateway credential cache sync",
)
+ # Gateway quota projection reconcile - every 15 min, offset from the quota-limiting run and
+ # the :05/:10 gateway cache refreshes, so a missed signal or an expiring blob heals within a tick
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="7,22,37,52"),
+ reconcile_llm_gateway_quota_projection.s(),
+ name="llm-gateway quota projection reconcile",
+ )
+
# Gateway credential last-used drain - every 5 min; the only writer of last_used_at for gateway keys.
sender.add_periodic_task(
crontab(minute="*/5"),
diff --git a/posthog/tasks/team_llm_gateway_quota.py b/posthog/tasks/team_llm_gateway_quota.py
new file mode 100644
index 000000000000..2b737e25ff39
--- /dev/null
+++ b/posthog/tasks/team_llm_gateway_quota.py
@@ -0,0 +1,67 @@
+"""Celery tasks that project the per-team quota blob the Go ai-gateway's credit-bucket gate reads."""
+
+import time
+
+from django.conf import settings
+
+import structlog
+from celery import shared_task
+
+from posthog.models.organization import Organization
+from posthog.storage.team_llm_gateway_quota_cache import (
+ project_org_quota,
+ project_teams_quota_by_token,
+ reconcile_quota_projection,
+)
+from posthog.tasks.utils import CeleryQueue
+
+logger = structlog.get_logger(__name__)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+def project_org_llm_gateway_quota_task(organization_id: str) -> None:
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return
+ try:
+ organization = Organization.objects.get(id=organization_id) # nosemgrep: celery-task-team-scope-audit
+ except Organization.DoesNotExist:
+ logger.debug("Organization does not exist for llm-gateway quota projection", organization_id=organization_id)
+ return
+ written = project_org_quota(organization)
+ logger.info(
+ "Projected llm-gateway quota for organization",
+ organization_id=organization_id,
+ is_active=organization.is_active,
+ blobs_written=written,
+ )
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+def project_teams_llm_gateway_quota_task(tokens: list[str]) -> None:
+ if not settings.AI_GATEWAY_REDIS_URL:
+ return
+ written = project_teams_quota_by_token(tokens)
+ logger.info("Projected llm-gateway quota for teams", teams=len(tokens), blobs_written=written)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
+def reconcile_llm_gateway_quota_projection() -> None:
+ """Heals a missed signal, an expiring deactivated-org blob, or a stray blob within a tick."""
+ if not settings.AI_GATEWAY_REDIS_URL:
+ logger.info("AI gateway Redis URL not set, skipping llm-gateway quota projection reconcile")
+ return
+ start_time = time.time()
+ try:
+ counts = reconcile_quota_projection()
+ logger.info(
+ "Completed llm-gateway quota projection reconcile",
+ **counts,
+ duration_seconds=time.time() - start_time,
+ )
+ except Exception as e:
+ logger.exception(
+ "Failed to complete llm-gateway quota projection reconcile",
+ error=str(e),
+ duration_seconds=time.time() - start_time,
+ )
+ raise
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index f28cbec45dda..c83f151e0bfb 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -154,6 +154,9 @@
'posthog.tasks.team_event_volume.update_team_event_volumes',
'posthog.tasks.team_llm_gateway_policy.refresh_expiring_llm_gateway_policy_cache_entries',
'posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task',
+ 'posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task',
+ 'posthog.tasks.team_llm_gateway_quota.project_teams_llm_gateway_quota_task',
+ 'posthog.tasks.team_llm_gateway_quota.reconcile_llm_gateway_quota_projection',
'posthog.tasks.team_metadata.cleanup_stale_expiry_tracking_task',
'posthog.tasks.team_metadata.refresh_expiring_team_metadata_cache_entries',
'posthog.tasks.team_metadata.update_related_teams_metadata_cache_task',
diff --git a/posthog/tasks/test/test_scheduled.py b/posthog/tasks/test/test_scheduled.py
index 7f3a6e1c4d57..5a33e4482b82 100644
--- a/posthog/tasks/test/test_scheduled.py
+++ b/posthog/tasks/test/test_scheduled.py
@@ -6,6 +6,7 @@ from parameterized import parameterized
from posthog.celery import app
from posthog.tasks.scheduled import instance_spread_minute, setup_periodic_tasks
+from posthog.tasks.team_llm_gateway_quota import reconcile_llm_gateway_quota_projection
class TestScheduledTasks(TestCase):
@@ -35,6 +36,21 @@ class TestPrivacyTaskScheduling(SimpleTestCase):
self.assertEqual(calls[0].args[1].type.queue, "ai_research_privacy")
+class TestLLMGatewayQuotaReconcileScheduling(SimpleTestCase):
+ def test_the_reconcile_runs_every_15_minutes(self) -> None:
+ sender = MagicMock()
+ setup_periodic_tasks(sender)
+ calls = [
+ call
+ for call in sender.add_periodic_task.call_args_list
+ if call.kwargs.get("name") == "llm-gateway quota projection reconcile"
+ ]
+ self.assertEqual(len(calls), 1)
+ schedule, signature = calls[0].args
+ self.assertEqual(schedule.minute, {7, 22, 37, 52})
+ self.assertEqual(signature.task, reconcile_llm_gateway_quota_projection.name)
+
+
class TestInstanceSpreadMinute(SimpleTestCase):
def test_one_installation_keeps_its_minute_in_every_process(self) -> None:
# A literal, because the minute has to survive a beat restart. A hash that
diff --git a/posthog/tasks/test/test_team_llm_gateway_quota.py b/posthog/tasks/test/test_team_llm_gateway_quota.py
new file mode 100644
index 000000000000..8b8128034634
--- /dev/null
+++ b/posthog/tasks/test/test_team_llm_gateway_quota.py
@@ -0,0 +1,128 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from posthog.models.organization import Organization
+from posthog.redis import get_client
+from posthog.storage.team_llm_gateway_quota_cache import (
+ LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET,
+ get_team_quota_blob,
+ projected_team_ids,
+ team_llm_gateway_quota_hypercache as hypercache,
+)
+from posthog.tasks.team_llm_gateway_quota import (
+ project_org_llm_gateway_quota_task,
+ project_teams_llm_gateway_quota_task,
+ reconcile_llm_gateway_quota_projection,
+)
+
+from ee.billing.quota_limiting import (
+ QuotaLimitingCaches,
+ QuotaResource,
+ add_limited_team_tokens,
+ remove_limited_team_tokens,
+)
+
+_GATEWAY_REDIS_URL = "redis://localhost:6379/15"
+
+
+class TestLLMGatewayQuotaTasks(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ hypercache.cache_client.clear()
+ get_client(hypercache.redis_url).delete(LLM_GATEWAY_QUOTA_CACHE_EXPIRY_SORTED_SET)
+ remove_limited_team_tokens(
+ QuotaResource.AI_CREDITS, [self.team.api_token], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
+ )
+
+ def tearDown(self) -> None:
+ remove_limited_team_tokens(
+ QuotaResource.AI_CREDITS, [self.team.api_token], QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
+ )
+ super().tearDown()
+
+ @patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+ def test_org_task_projects_every_team(self, mock_settings: MagicMock) -> None:
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ Organization.objects.filter(id=self.organization.id).update(is_active=False)
+ with self.settings(AI_GATEWAY_REDIS_URL=_GATEWAY_REDIS_URL):
+ project_org_llm_gateway_quota_task(str(self.organization.id))
+ blob = get_team_quota_blob(self.team)
+ assert blob is not None
+ self.assertTrue(blob["org_deactivated"])
+
+ def test_org_task_ignores_a_missing_org(self) -> None:
+ with self.settings(AI_GATEWAY_REDIS_URL=_GATEWAY_REDIS_URL):
+ project_org_llm_gateway_quota_task("00000000-0000-0000-0000-000000000000")
+
+ @patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+ def test_reconcile_task_projects_limited_teams(self, mock_settings: MagicMock) -> None:
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ add_limited_team_tokens(
+ QuotaResource.AI_CREDITS,
+ {self.team.api_token: int((timezone.now() + timedelta(days=2)).timestamp())},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+ with self.settings(AI_GATEWAY_REDIS_URL=_GATEWAY_REDIS_URL):
+ reconcile_llm_gateway_quota_projection()
+ self.assertEqual(projected_team_ids(), {self.team.id})
+
+ @patch("posthog.storage.team_llm_gateway_quota_cache.settings")
+ def test_teams_task_projects_the_teams_behind_the_tokens(self, mock_settings: MagicMock) -> None:
+ mock_settings.AI_GATEWAY_REDIS_URL = _GATEWAY_REDIS_URL
+ add_limited_team_tokens(
+ QuotaResource.AI_CREDITS,
+ {self.team.api_token: int((timezone.now() + timedelta(days=2)).timestamp())},
+ QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY,
+ )
+ with self.settings(AI_GATEWAY_REDIS_URL=_GATEWAY_REDIS_URL):
+ project_teams_llm_gateway_quota_task([self.team.api_token])
+ self.assertEqual(projected_team_ids(), {self.team.id})
+
+ def test_teams_task_noop_without_gateway_redis_url(self) -> None:
+ with (
+ self.settings(AI_GATEWAY_REDIS_URL=None),
+ patch("posthog.tasks.team_llm_gateway_quota.project_teams_quota_by_token") as project,
+ ):
+ project_teams_llm_gateway_quota_task([self.team.api_token])
+ project.assert_not_called()
+
+ def test_reconcile_task_noop_without_gateway_redis_url(self) -> None:
+ with (
+ self.settings(AI_GATEWAY_REDIS_URL=None),
+ patch("posthog.tasks.team_llm_gateway_quota.reconcile_quota_projection") as reconcile,
+ ):
+ reconcile_llm_gateway_quota_projection()
+ reconcile.assert_not_called()
+
+ def test_deactivating_an_org_enqueues_the_projection(self) -> None:
+ with (
+ self.settings(AI_GATEWAY_REDIS_URL=_GATEWAY_REDIS_URL),
+ patch("posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay") as delay,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ self.organization.is_active = False
+ self.organization.save()
+ delay.assert_called_once_with(str(self.organization.id))
+
+ def test_deactivating_an_org_enqueues_nothing_without_gateway_redis_url(self) -> None:
+ with (
+ self.settings(AI_GATEWAY_REDIS_URL=None),
+ patch("posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay") as delay,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ self.organization.is_active = False
+ self.organization.save()
+ delay.assert_not_called()
+
+ def test_saving_an_org_without_an_active_flip_enqueues_nothing(self) -> None:
+ with (
+ patch("posthog.tasks.team_llm_gateway_quota.project_org_llm_gateway_quota_task.delay") as delay,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ self.organization.name = "renamed"
+ self.organization.save()
+ delay.assert_not_called()
diff --git a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json b/products/desktop/packages/agent/src/utils/gateway-routing-cases.json
index c41619bf069c..8b271a4b76be 100644
--- a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json
+++ b/products/desktop/packages/agent/src/utils/gateway-routing-cases.json
@@ -202,6 +202,20 @@
"allowlist": "signals_scout",
"expected": false
},
+ {
+ "origin_product": "loop",
+ "ai_stage": null,
+ "internal": false,
+ "allowlist": "posthog_code",
+ "expected": true
+ },
+ {
+ "origin_product": "user_created",
+ "ai_stage": null,
+ "internal": false,
+ "allowlist": "signals_scout,posthog_code",
+ "expected": true
+ },
{
"origin_product": "workflow",
"ai_stage": null,
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 82b20fe103c3..dce6733ef3ce 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -2,13 +2,16 @@ from enum import StrEnum
from typing import TYPE_CHECKING
from django.conf import settings
+from django.core.cache import cache
+
+import structlog
from posthog.cloud_utils import get_cached_instance_license
from posthog.models.user import User
from posthog.ph_client import feature_enabled_or_false, get_feature_flag_or_none
from products.tasks.backend.facade.contracts import DesktopAccessReason
-from products.tasks.backend.metrics import observe_desktop_access_decision
+from products.tasks.backend.metrics import DesktopAccessOutcome, observe_desktop_access_decision
from ee.billing.billing_manager import (
BillingManager,
@@ -21,7 +24,10 @@ if TYPE_CHECKING:
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+logger = structlog.get_logger(__name__)
+
DESKTOP_ACCESS_OVERRIDE_FLAG = "posthog-desktop-access-override"
+_FUNDING_DECISION_CACHE_KEY = "desktop_access_funding_decision:{organization_id}"
class DesktopAccessResolutionError(Exception):
@@ -53,7 +59,48 @@ def _get_funding_status(user: User, organization: "Organization") -> Organizatio
raise DesktopAccessResolutionError("Could not resolve organization funding status") from error
-def get_desktop_access_decision(user: User, organization: "Organization") -> DesktopAccessDecision:
+_DECISION_OUTCOMES: dict[DesktopAccessDecision, DesktopAccessOutcome] = {
+ DesktopAccessDecision.ALLOWED: "allowed",
+ DesktopAccessDecision.STARTUP_PLAN: "startup_plan",
+ DesktopAccessDecision.PREPAID_CREDITS: "prepaid_credits",
+}
+
+
+_DECISION_VALUES = frozenset(decision.value for decision in DesktopAccessDecision)
+
+
+def _funding_decision(user: User, organization: "Organization") -> DesktopAccessDecision:
+ funding_status = _get_funding_status(user, organization)
+ if funding_status.startup_program_label is not None:
+ return DesktopAccessDecision.STARTUP_PLAN
+ if funding_status.prepaid_credit_state in {PrepaidCreditState.PENDING, PrepaidCreditState.ACTIVE}:
+ return DesktopAccessDecision.PREPAID_CREDITS
+ return DesktopAccessDecision.ALLOWED
+
+
+def _cached_funding_decision(user: User, organization: "Organization", cache_seconds: int) -> DesktopAccessDecision:
+ """A cache error falls through to the live lookup; a resolution failure is never cached."""
+ cache_key = _FUNDING_DECISION_CACHE_KEY.format(organization_id=organization.id)
+ try:
+ cached = cache.get(cache_key)
+ except Exception:
+ logger.warning("desktop_access_decision_cache_read_failed", exc_info=True)
+ cached = None
+ if isinstance(cached, str) and cached in _DECISION_VALUES:
+ return DesktopAccessDecision(cached)
+ decision = _funding_decision(user, organization)
+ try:
+ cache.set(cache_key, decision.value, timeout=cache_seconds)
+ except Exception:
+ logger.warning("desktop_access_decision_cache_write_failed", exc_info=True)
+ return decision
+
+
+def get_desktop_access_decision(
+ user: User, organization: "Organization", *, funding_cache_seconds: int = 0
+) -> DesktopAccessDecision:
+ """`funding_cache_seconds` caches the billing funding lookup per org; the per-user override
+ flag is evaluated on every call."""
if not user or not user.is_authenticated or not user.distinct_id:
raise DesktopAccessResolutionError("Authentication is required to evaluate Desktop access")
@@ -80,20 +127,16 @@ def get_desktop_access_decision(user: User, organization: "Organization") -> Des
return DesktopAccessDecision.ALLOWED
try:
- funding_status = _get_funding_status(user, organization)
+ if funding_cache_seconds > 0:
+ decision = _cached_funding_decision(user, organization, funding_cache_seconds)
+ else:
+ decision = _funding_decision(user, organization)
except DesktopAccessResolutionError:
observe_desktop_access_decision(outcome="resolution_failure")
raise
- if funding_status.startup_program_label is not None:
- observe_desktop_access_decision(outcome="startup_plan")
- return DesktopAccessDecision.STARTUP_PLAN
- if funding_status.prepaid_credit_state in {PrepaidCreditState.PENDING, PrepaidCreditState.ACTIVE}:
- observe_desktop_access_decision(outcome="prepaid_credits")
- return DesktopAccessDecision.PREPAID_CREDITS
-
- observe_desktop_access_decision(outcome="allowed")
- return DesktopAccessDecision.ALLOWED
+ observe_desktop_access_decision(outcome=_DECISION_OUTCOMES[decision])
+ return decision
def has_loops_access(user: User, team: "Team | None" = None) -> bool:
diff --git a/products/tasks/backend/facade/desktop_gateway.py b/products/tasks/backend/facade/desktop_gateway.py
new file mode 100644
index 000000000000..c5818f841db6
--- /dev/null
+++ b/products/tasks/backend/facade/desktop_gateway.py
@@ -0,0 +1,31 @@
+from products.tasks.backend.logic.services.desktop_gateway_token import (
+ CREDIT_BUCKET_EXHAUSTED_DENIAL,
+ DESKTOP_AGENT_MODELS,
+ POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL,
+ POSTHOG_CODE_PRODUCT,
+ DesktopGatewayMintError,
+ _team_credit_refusal as team_credit_refusal,
+ desktop_gateway_base_url,
+ desktop_gateway_configured,
+ desktop_rollout_enabled,
+ desktop_token_ttl_seconds,
+ mint_desktop_gateway_token,
+ plan_allowed_models,
+ posthog_code_plan,
+)
+
+__all__ = [
+ "CREDIT_BUCKET_EXHAUSTED_DENIAL",
+ "DESKTOP_AGENT_MODELS",
+ "POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL",
+ "POSTHOG_CODE_PRODUCT",
+ "DesktopGatewayMintError",
+ "desktop_gateway_base_url",
+ "desktop_gateway_configured",
+ "desktop_rollout_enabled",
+ "desktop_token_ttl_seconds",
+ "mint_desktop_gateway_token",
+ "plan_allowed_models",
+ "posthog_code_plan",
+ "team_credit_refusal",
+]
diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
index 755ecf4bb34b..2cc596c6591a 100644
--- a/products/tasks/backend/logic/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -3,21 +3,13 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast
from uuid import UUID
-from django.conf import settings
-
-import requests
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.auth import OAuthAccessTokenAuthentication
-from posthog.models import OAuthAccessToken
from posthog.permissions import get_authenticator_scopes
-
-if TYPE_CHECKING:
- from posthog.models import Organization, User
-from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS, create_oauth_access_token_for_user
-from posthog.utils import get_instance_region
+from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
from products.tasks.backend.access import DesktopAccessResolutionError, get_desktop_access_decision
from products.tasks.backend.facade.contracts import DesktopAccessReason
@@ -29,106 +21,41 @@ from products.tasks.backend.logic.services.compute_quota import (
from products.tasks.backend.metrics import observe_code_usage_gate_check
from products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer
-logger = logging.getLogger(__name__)
-
-GATEWAY_PRODUCT = "posthog_code"
+if TYPE_CHECKING:
+ from posthog.models import Organization, User
-# Short timeout: this runs on the creation hot path; on failure we fail open.
-GATEWAY_USAGE_TIMEOUT_SECONDS = 2.5
+logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class CodeUsageStatus:
is_rate_limited: bool
limit_type: str | None # "burst" (daily) | "sustained" (monthly) | None
- reset_at: str | None # ISO 8601 string from the gateway, when known
+ reset_at: str | None # ISO 8601, the billing period end when known
is_pro: bool
-def _gateway_usage_url() -> str | None:
- """Resolve the LLM gateway usage endpoint for this deployment.
-
- Region-based in cloud, the local gateway (localhost:3308, matching the
- desktop client) under DEBUG. Returns None when no gateway applies, so
- callers fail open.
- """
- region = get_instance_region()
- if region == "US":
- base = "https://gateway.us.posthog.com"
- elif region == "EU":
- base = "https://gateway.eu.posthog.com"
- elif settings.DEBUG:
- base = "http://localhost:3308"
- else:
- return None
- return f"{base}/v1/usage/{GATEWAY_PRODUCT}"
-
-
-def _parse_usage(data: dict[str, Any]) -> CodeUsageStatus:
- sustained = data.get("sustained") or {}
- burst = data.get("burst") or {}
- sustained_exceeded = bool(sustained.get("exceeded"))
- burst_exceeded = bool(burst.get("exceeded"))
- is_limited = bool(data.get("is_rate_limited")) or sustained_exceeded or burst_exceeded
+def get_posthog_code_usage(team_id: int) -> CodeUsageStatus | None:
+ """None (fail open) on any failure, so a Redis or DB error never blocks task creation."""
+ from posthog.models import Team # noqa: PLC0415
- # Surface the bucket that's actually over for the reset hint; burst (daily) takes priority.
- if burst_exceeded:
- limit_type, reset_at = "burst", burst.get("reset_at")
- elif sustained_exceeded:
- limit_type, reset_at = "sustained", sustained.get("reset_at")
- else:
- limit_type, reset_at = None, None
-
- return CodeUsageStatus(
- is_rate_limited=is_limited,
- limit_type=limit_type,
- reset_at=reset_at,
- is_pro=bool(data.get("is_pro")),
- )
-
-
-def get_posthog_code_usage(user, team_id: int) -> CodeUsageStatus | None:
- """Fetch the team's posthog_code usage from the LLM gateway.
-
- Returns None (fail open) on any failure — gateway hiccups must never block
- task creation. Mints a short-lived, least-privilege `llm_gateway:read` token
- the same way the sandbox agent authenticates to the gateway.
- """
- url = _gateway_usage_url()
- if not url:
- return None
+ from ee.billing.quota_limiting import QuotaResource, is_team_over_credit_budget # noqa: PLC0415
try:
- token = create_oauth_access_token_for_user(
- user, team_id, scopes=["llm_gateway:read"], include_internal_scopes=False
- )
+ team = Team.objects.select_related("organization").get(id=team_id)
+ limited = is_team_over_credit_budget(team.api_token, QuotaResource.POSTHOG_CODE_CREDITS)
+ if not limited:
+ return CodeUsageStatus(is_rate_limited=False, limit_type=None, reset_at=None, is_pro=False)
+ period = team.organization.current_billing_period
except Exception:
- logger.warning("code_usage_gate: failed to mint gateway token", exc_info=True)
+ logger.warning("code_usage_gate: credit bucket check failed", exc_info=True)
return None
-
- try:
- response = requests.get(
- url,
- headers={"Authorization": f"Bearer {token}"},
- timeout=GATEWAY_USAGE_TIMEOUT_SECONDS,
- )
- if response.status_code != 200:
- logger.warning("code_usage_gate: gateway usage returned %s", response.status_code)
- return None
- return _parse_usage(response.json())
- except requests.RequestException:
- logger.warning("code_usage_gate: gateway usage request failed", exc_info=True)
- return None
- except (ValueError, AttributeError):
- logger.warning("code_usage_gate: could not parse gateway usage response", exc_info=True)
- return None
- finally:
- # Short-lived token: delete it so repeated gate checks don't pile up OAuthAccessToken rows.
- # Swallow cleanup errors so a DB hiccup here can't break the fail-open guarantee.
- try:
- OAuthAccessToken.objects.filter(token=token).delete()
- except Exception:
- logger.warning("code_usage_gate: failed to delete gateway token", exc_info=True)
+ return CodeUsageStatus(
+ is_rate_limited=True,
+ limit_type=None,
+ reset_at=period.end.isoformat() if period else None,
+ is_pro=False,
+ )
def rate_limit_error_payload(usage: CodeUsageStatus) -> dict[str, Any]:
@@ -257,16 +184,15 @@ 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.
The cost backstop on cloud runs, applied on top of the entitlement gate above. 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. Deactivated organizations are blocked
- locally first, so that block holds even when the gateway check fails open.
+ open when the credit bucket can't be read, so every check is counted by outcome
+ (`checked_allowed` / `checked_blocked` / `fail_open`) and a silently removed backstop is
+ visible, not just logged. Deactivated organizations are blocked first.
"""
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)
+ usage = get_posthog_code_usage(team_id)
if usage is None:
observe_code_usage_gate_check(outcome="fail_open")
return None
diff --git a/products/tasks/backend/logic/services/desktop_gateway_token.py b/products/tasks/backend/logic/services/desktop_gateway_token.py
new file mode 100644
index 000000000000..c62329f9eb2b
--- /dev/null
+++ b/products/tasks/backend/logic/services/desktop_gateway_token.py
@@ -0,0 +1,250 @@
+"""PostHog Desktop (`posthog_code`) tokens on the Go ai-gateway.
+
+Shared by the desktop app's mint endpoint and the sandbox worker's mint, so it stays free of
+Temporal imports.
+"""
+
+import json
+import logging
+import functools
+from collections.abc import Mapping
+from decimal import Decimal, InvalidOperation
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Any, Literal
+
+from django.conf import settings
+
+import requests
+import posthoganalytics
+from prometheus_client import Counter
+
+from posthog.constants import AvailableFeature
+from posthog.exceptions_capture import capture_exception
+from posthog.ph_client import feature_enabled_or_false
+
+from products.tasks.backend.logic.services.gateway_model_pin import DESKTOP_AGENT_MODELS, FREE_TIER_MODELS
+
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+logger = logging.getLogger(__name__)
+
+POSTHOG_CODE_PRODUCT = "posthog_code"
+
+# Mirrors PRODUCTS[*].credit_bucket in services/llm-gateway/src/llm_gateway/products/config.py.
+# Both gateways refuse an exhausted bucket, and a mint checks it first so a capped or deactivated
+# org never gets a token.
+PRODUCT_CREDIT_BUCKET: dict[str, str] = {
+ "posthog_ai": "ai_credits",
+ "posthog_code": "posthog_code_credits",
+ "slack_app": "ai_credits",
+ "workflows": "ai_credits",
+}
+
+# The legacy gateway's refusal for an exhausted Desktop bucket; the app matches on it.
+POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL = (
+ "Your team has reached its PostHog Desktop usage limit for this billing period. "
+ "See https://app.posthog.com/organization/billing for your usage and limits."
+)
+CREDIT_BUCKET_EXHAUSTED_DENIAL = "credit_bucket_exhausted:posthog_code_credits"
+
+_MAX_CAP_USD = Decimal("10000")
+_MAX_CAP_DECIMAL_PLACES = 6
+
+_MIN_TTL_SECONDS = 60
+_MAX_TTL_SECONDS = 86400
+
+# One attempt on the web request path: the app falls back to the legacy gateway and retries later,
+# so a slow gateway must not hold the worker.
+_MINT_TIMEOUT_SECONDS = 3
+
+PosthogCodePlan = Literal["paid", "free"]
+
+DESKTOP_GATEWAY_MINTS = Counter(
+ "posthog_desktop_gateway_token_mints_total",
+ "PostHog Desktop gateway token mints, by outcome (ok/rate_limited/refused/unreachable/malformed)",
+ labelnames=["outcome"],
+)
+
+
+def _team_credit_refusal(team_id: int, bucket: str) -> str | None:
+ from posthog.models import Team # noqa: PLC0415
+
+ from ee.billing.quota_limiting import QuotaResource, is_team_over_credit_budget # noqa: PLC0415
+
+ row = Team.objects.filter(id=team_id).values_list("api_token", "organization__is_active").first()
+ if not row:
+ return None
+ api_token, org_active = row
+ if org_active is False:
+ return "org_deactivated"
+ if api_token and is_team_over_credit_budget(api_token, QuotaResource(bucket)):
+ return f"{bucket}_exhausted"
+ return None
+
+
+def _report_invalid_caps(setting_name: str, problem: str) -> None:
+ logger.warning("Ignoring invalid cap setting %s: %s", setting_name, problem)
+ # The mint path calls this, so keep the request's locals out of the capture.
+ with posthoganalytics.new_context():
+ posthoganalytics.set_capture_exception_code_variables_context(False)
+ capture_exception(ValueError(f"{setting_name} {problem}"), {"setting": setting_name})
+
+
+def _valid_cap(value: object, setting_name: str) -> str | None:
+ try:
+ cap = Decimal(str(value))
+ except (InvalidOperation, ValueError):
+ logger.warning("Ignoring invalid cap for %s", setting_name)
+ return None
+ if not cap.is_finite():
+ logger.warning("Ignoring invalid cap for %s", setting_name)
+ return None
+ exponent = cap.as_tuple().exponent
+ if not isinstance(exponent, int):
+ logger.warning("Ignoring invalid cap for %s", setting_name)
+ return None
+ decimal_places = max(0, -exponent)
+ if cap <= 0 or cap > _MAX_CAP_USD or decimal_places > _MAX_CAP_DECIMAL_PLACES:
+ logger.warning("Ignoring invalid cap for %s", setting_name)
+ return None
+ return f"{cap:f}"
+
+
[email protected]_cache(maxsize=32)
+def valid_caps(raw: str, setting_name: str) -> Mapping[str, str]:
+ """Parsed once per value per process. A malformed map or entry is captured, because every mint
+ would otherwise fall back to a default in silence."""
+ if not raw:
+ return MappingProxyType({})
+ try:
+ parsed = json.loads(raw)
+ except ValueError:
+ parsed = None
+ if not isinstance(parsed, dict):
+ _report_invalid_caps(setting_name, "is not a JSON object")
+ return MappingProxyType({})
+ caps: dict[str, str] = {}
+ invalid: list[str] = []
+ for key, value in parsed.items():
+ cap = _valid_cap(value, setting_name)
+ if cap is None:
+ invalid.append(str(key))
+ else:
+ caps[str(key)] = cap
+ if invalid:
+ _report_invalid_caps(setting_name, f"has invalid entries for {sorted(invalid)}")
+ return MappingProxyType(caps)
+
+
+def _cap_override(raw: str, key: str, setting_name: str) -> str | None:
+ return valid_caps(raw, setting_name).get(key)
+
+
+def posthog_code_plan(team: "Team") -> PosthogCodePlan:
+ """`paid` when the org is active and billing grants Desktop usage; the rule `quota_limits` reports."""
+ organization = team.organization
+ if organization.is_active is not False and organization.is_feature_available(AvailableFeature.POSTHOG_CODE_USAGE):
+ return "paid"
+ return "free"
+
+
+def plan_allowed_models(plan: PosthogCodePlan) -> list[str]:
+ return list(DESKTOP_AGENT_MODELS) if plan == "paid" else list(FREE_TIER_MODELS)
+
+
+def desktop_rollout_enabled(organization: "Organization", team: "Team", distinct_id: str | None = None) -> bool:
+ """The rollout flag, targeted on the org. A flag outage reads as off, which keeps both legs on legacy."""
+ organization_id = str(organization.id)
+ try:
+ return feature_enabled_or_false(
+ settings.DESKTOP_GATEWAY_ROLLOUT_FLAG,
+ distinct_id or organization_id,
+ groups={"organization": organization_id, "project": str(team.id)},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("desktop_gateway_token: rollout flag unavailable, treating as off", exc_info=True)
+ return False
+
+
+class DesktopGatewayMintError(Exception):
+ def __init__(self, message: str, *, rate_limited: bool = False) -> None:
+ super().__init__(message)
+ self.rate_limited = rate_limited
+
+
+def desktop_gateway_configured() -> bool:
+ return bool(settings.DESKTOP_GATEWAY_URL and settings.DESKTOP_GATEWAY_MINT_KEY)
+
+
+def desktop_gateway_base_url() -> str:
+ return (settings.DESKTOP_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")
+
+
[email protected]_cache(maxsize=8)
+def _valid_default_cap(raw: str, setting_name: str) -> str | None:
+ cap = _valid_cap(raw, setting_name)
+ if cap is None:
+ _report_invalid_caps(setting_name, "is not a valid cap")
+ return cap
+
+
+def desktop_token_cap_usd(team_id: int) -> str:
+ team_cap = _cap_override(
+ settings.DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES, str(team_id), "desktop token cap overrides"
+ )
+ if team_cap is not None:
+ return team_cap
+ return _valid_default_cap(settings.DESKTOP_GATEWAY_TOKEN_CAP_USD, "desktop token cap") or "200"
+
+
+def desktop_token_ttl_seconds() -> int:
+ return max(_MIN_TTL_SECONDS, min(int(settings.DESKTOP_GATEWAY_TOKEN_TTL_SECONDS), _MAX_TTL_SECONDS))
+
+
+def mint_desktop_gateway_token(*, team_id: int, user: str, allowed_models: list[str]) -> dict[str, Any]:
+ """Mint one session token; returns Go's body. Raises DesktopGatewayMintError on any refusal or
+ transport failure; the bearer never appears in logs or exception text."""
+ body = {
+ "cap_usd": desktop_token_cap_usd(team_id),
+ "ttl_seconds": desktop_token_ttl_seconds(),
+ "product": POSTHOG_CODE_PRODUCT,
+ "obo": str(team_id),
+ "user": user,
+ "allowed_models": allowed_models,
+ }
+ try:
+ response = requests.post(
+ f"{desktop_gateway_base_url()}/v1/tokens",
+ json=body,
+ headers={"Authorization": f"Bearer {settings.DESKTOP_GATEWAY_MINT_KEY}"},
+ timeout=_MINT_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as e:
+ DESKTOP_GATEWAY_MINTS.labels(outcome="unreachable").inc()
+ logger.warning("desktop gateway mint: transport failure (%s)", type(e).__name__)
+ raise DesktopGatewayMintError("gateway unreachable") from e
+
+ if response.status_code == 429:
+ # The mint key's per-minute ceiling (see DESKTOP_GATEWAY_TOKEN_TTL_SECONDS), shared by every user.
+ DESKTOP_GATEWAY_MINTS.labels(outcome="rate_limited").inc()
+ logger.warning("desktop_gateway_token: mint rate limited by the gateway (status=429)")
+ raise DesktopGatewayMintError("mint rate limited with HTTP 429", rate_limited=True)
+ if response.status_code != 201:
+ DESKTOP_GATEWAY_MINTS.labels(outcome="refused").inc()
+ logger.warning("desktop gateway mint: refused (status=%s)", response.status_code)
+ raise DesktopGatewayMintError(f"mint refused with HTTP {response.status_code}")
+ try:
+ minted = response.json()
+ except ValueError as e:
+ DESKTOP_GATEWAY_MINTS.labels(outcome="malformed").inc()
+ raise DesktopGatewayMintError("mint response was not JSON") from e
+ if not isinstance(minted, dict) or not minted.get("token") or not minted.get("expires_at"):
+ DESKTOP_GATEWAY_MINTS.labels(outcome="malformed").inc()
+ raise DesktopGatewayMintError("mint response missing token or expires_at")
+ DESKTOP_GATEWAY_MINTS.labels(outcome="ok").inc()
+ return minted
diff --git a/products/tasks/backend/logic/services/gateway_model_pin.py b/products/tasks/backend/logic/services/gateway_model_pin.py
index 377d730890b9..3a343a44026f 100644
--- a/products/tasks/backend/logic/services/gateway_model_pin.py
+++ b/products/tasks/backend/logic/services/gateway_model_pin.py
@@ -17,8 +17,26 @@ _FIRST_PARTY_AGENT_MODELS: list[str] = list(
dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS if "/" not in model.id)])
)
+# Ids the legacy gateway serves to PostHog Desktop that the catalog lacks; older app builds call them.
+_DESKTOP_LEGACY_MODELS: tuple[str, ...] = ("gpt-5.4", "gpt-5.3-codex", "gpt-5.2", "gpt-5-mini")
+
+# Every model a PostHog Desktop session or cloud run may call, slash ids included. Go picks the provider.
+DESKTOP_AGENT_MODELS: list[str] = list(
+ dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS), *_DESKTOP_LEGACY_MODELS])
+)
+# The Go gateway refuses a pin longer than this at mint.
+MAX_GATEWAY_PIN_LENGTH = 32
+assert len(DESKTOP_AGENT_MODELS) <= MAX_GATEWAY_PIN_LENGTH, "the desktop model pin outgrew the gateway limit"
+
+FREE_TIER_MODELS: list[str] = ["@cf/zai-org/glm-5.2", "deepseek-ai/deepseek-v4-flash-0731", "moonshotai/kimi-k3"]
+
+# Stamped on a free-plan run in place of its product, so the model-change guard reads the narrower pin.
+FREE_TIER_PIN_KEY = "posthog_code:free"
+
PRODUCT_ALLOWED_MODELS: dict[str, list[str]] = {
"posthog_ai": _FIRST_PARTY_AGENT_MODELS,
+ "posthog_code": DESKTOP_AGENT_MODELS,
+ FREE_TIER_PIN_KEY: FREE_TIER_MODELS,
"review_hog": _FIRST_PARTY_AGENT_MODELS,
"slack_app": _FIRST_PARTY_AGENT_MODELS,
"workflows": _FIRST_PARTY_AGENT_MODELS,
diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.py
index b972a27b6b02..419ce14fe97a 100644
--- a/products/tasks/backend/logic/services/workflow_tasks.py
+++ b/products/tasks/backend/logic/services/workflow_tasks.py
@@ -220,14 +220,9 @@ def create_workflow_task(
observe_workflow_task_create(reason="owner_ineligible")
raise WorkflowTaskOwnerIneligible()
- # Fast, unlocked pre-checks before the gate call below. The gate mints an
- # OAuthAccessToken for gate_owner and makes a blocking request to the LLM gateway, so
- # an owner who already lost team access, or a workflow that's already past its daily
- # cap, must not reach it: checking first means neither pays for that mint-and-call on
- # every trigger event. These reads are not authoritative, since nothing holds the
- # advisory locks here yet, so a concurrent write can move the counts after this check
- # runs. The same checks run again under the locks below, and that locked run is the
- # one that decides.
+ # Fast, unlocked pre-checks so an ineligible owner or a capped workflow never reaches
+ # the gate. Nothing holds the advisory locks yet, so these reads are not authoritative;
+ # the same checks run again under the locks below, and that run decides.
if not user_has_current_team_access(gate_owner, team):
observe_workflow_task_create(reason="owner_ineligible")
raise WorkflowTaskOwnerIneligible()
@@ -239,10 +234,9 @@ def create_workflow_task(
observe_workflow_task_create(reason="team_rate_capped")
raise WorkflowTaskTeamRateCapped(team_rate_cap)
- # The gate stays outside the transaction: it calls the LLM gateway (short timeout,
- # fails open), and holding the advisory locks across an external call would stall
- # every workflow fire for the team. Replays never reach it, so engine retries of an
- # already-created task succeed even for a blocked owner.
+ # The gate stays outside the transaction: it reads Redis (fails open), and holding the
+ # advisory locks across it would stall every workflow fire for the team. Replays never
+ # reach it, so engine retries of an already-created task succeed even for a blocked owner.
if usage_limit_response(gate_owner, team.id) is not None:
observe_workflow_task_create(reason="gate_blocked")
raise WorkflowTaskUsageLimited()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 98c27cbaa22c..52d92e3b87d6 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -5123,3 +5123,35 @@ class TasksUserConfigResponseSerializer(serializers.Serializer):
resolved_ai_run_defaults = TasksResolvedAIRunDefaultsSerializer(
help_text="The defaults a new run will use when no explicit runtime selection is sent."
)
+
+
+class DesktopGatewayTokenRefusalSerializer(serializers.Serializer):
+ enabled = serializers.BooleanField()
+ reason = serializers.CharField()
+ detail = serializers.CharField(required=False)
+ access = serializers.DictField(required=False)
+
+
+class DesktopGatewayTokenSerializer(serializers.Serializer):
+ enabled = serializers.BooleanField()
+ token = serializers.CharField()
+ expires_at = serializers.CharField()
+ cap_usd = serializers.JSONField(allow_null=True)
+ gateway_url = serializers.CharField()
+ product = serializers.CharField()
+ team_id = serializers.IntegerField()
+ plan = serializers.CharField()
+ allowed_models = serializers.ListField(child=serializers.CharField())
+ product_models = serializers.ListField(child=serializers.CharField())
+
+
+class DesktopUsageSerializer(serializers.Serializer):
+ product = serializers.CharField()
+ user_id = serializers.IntegerField()
+ burst = serializers.JSONField()
+ sustained = serializers.JSONField()
+ ai_credits = serializers.JSONField()
+ is_rate_limited = serializers.BooleanField()
+ is_pro = serializers.BooleanField()
+ code_usage_subscribed = serializers.BooleanField()
+ billing_period_end = serializers.CharField(allow_null=True)
diff --git a/products/tasks/backend/presentation/views/desktop_access.py b/products/tasks/backend/presentation/views/desktop_access.py
index 011f1b1dd4dd..078cf1c1f417 100644
--- a/products/tasks/backend/presentation/views/desktop_access.py
+++ b/products/tasks/backend/presentation/views/desktop_access.py
@@ -1,23 +1,157 @@
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
+from django.conf import settings
+from django.utils import timezone
+
+import posthoganalytics
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.throttling import UserRateThrottle
+from posthog.api.email_verification import email_verification_pending
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.exceptions_capture import capture_exception
+from posthog.llm.wizard_blocklist import wizard_identity_blocked
from posthog.models import User
+from posthog.models.oauth import OAuthAccessToken
from posthog.permissions import APIScopePermission
+from posthog.storage.gateway_credential_cache import GATEWAY_CREDENTIAL_REQUIRED_SCOPE, oauth_credential_authorized
+from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS
-from products.tasks.backend.facade.access import DesktopAccessResolutionError, get_desktop_access_decision
+from products.tasks.backend.facade.access import (
+ DesktopAccessResolutionError,
+ compute_quota_limit_response,
+ get_desktop_access_decision,
+)
+from products.tasks.backend.facade.contracts import ComputeQuotaDenialReason
+from products.tasks.backend.facade.desktop_gateway import (
+ CREDIT_BUCKET_EXHAUSTED_DENIAL,
+ DESKTOP_AGENT_MODELS,
+ POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL,
+ POSTHOG_CODE_PRODUCT,
+ DesktopGatewayMintError,
+ desktop_gateway_base_url,
+ desktop_gateway_configured,
+ desktop_rollout_enabled,
+ desktop_token_ttl_seconds,
+ mint_desktop_gateway_token,
+ plan_allowed_models,
+ posthog_code_plan,
+ team_credit_refusal,
+)
from products.tasks.backend.presentation.serializers import (
DesktopAccessResponseSerializer,
+ DesktopGatewayTokenRefusalSerializer,
+ DesktopGatewayTokenSerializer,
+ DesktopUsageSerializer,
TaskRunErrorResponseSerializer,
)
+from ee.billing.quota_limiting import team_quota_snapshot
+
+# The legacy gateway's usage windows for posthog_code, which its cost throttles exempt.
+_BURST_WINDOW_SECONDS = 86400
+_SUSTAINED_WINDOW_SECONDS = 2592000
+_USD_PER_CREDIT = 0.01
+_DESKTOP_COMPONENT_RESOURCES = {
+ "token_credits": "posthog_code_token_credits",
+ "compute_credits": "sandbox_compute_credits",
+ "cpu_millicore_seconds": "sandbox_compute_cpu_millicore_seconds",
+ "memory_mib_seconds": "sandbox_compute_memory_mib_seconds",
+}
+
+_DESKTOP_ACCESS_MESSAGES = {
+ "startup_plan": "PostHog Desktop isn't available for Startup or YC program organizations.",
+ "prepaid_credits": "PostHog Desktop isn't available while this organization has prepaid credits.",
+}
+
+
+class DesktopGatewayTokenThrottle(UserRateThrottle):
+ """Every desktop caller's request spends a slot, refusals included."""
+
+ scope = "desktop_gateway_token"
+
+ def get_rate(self) -> str:
+ return f"{int(settings.DESKTOP_GATEWAY_MINTS_PER_HOUR)}/hour"
+
+
+def _disabled(reason: str, http_status: int = status.HTTP_200_OK, **extra: Any) -> Response:
+ payload = {"enabled": False, "reason": reason, **extra}
+ return Response(DesktopGatewayTokenRefusalSerializer(payload).data, status=http_status)
+
+
+def _desktop_oauth_credential(request: Request) -> tuple[OAuthAccessToken | None, Response | None]:
+ authenticator = getattr(request, "successful_authenticator", None)
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return None, _disabled("oauth_required", status.HTTP_403_FORBIDDEN, detail="Sign in with PostHog Desktop.")
+ access_token = authenticator.access_token
+ application = getattr(access_token, "application", None)
+ client_id = getattr(application, "client_id", None)
+ # The raw scope text: `*` and filtered scope lists must not stand in for the gateway scope.
+ raw_scopes = (access_token.scope or "").split()
+ if (
+ client_id not in POSTHOG_CODE_OAUTH_APP_CLIENT_IDS
+ or GATEWAY_CREDENTIAL_REQUIRED_SCOPE not in raw_scopes
+ # Sandbox tokens mint through the worker, under the run's own cap and lifetime.
+ or "internal_run:read" in raw_scopes
+ or access_token.sandbox_task_id is not None
+ or access_token.impersonated_by_id is not None
+ ):
+ return None, _disabled(
+ "oauth_required",
+ status.HTTP_403_FORBIDDEN,
+ detail="This credential cannot mint PostHog Desktop gateway tokens.",
+ )
+ return access_token, None
+
+
+def _iso(value: datetime) -> str:
+ return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
+
+
+def _exempt_window(now: datetime, window_seconds: int) -> dict[str, Any]:
+ return {
+ "used_percent": 0.0,
+ "resets_in_seconds": window_seconds,
+ "reset_at": _iso(now + timedelta(seconds=window_seconds)),
+ "exceeded": False,
+ }
+
+
+def _optional_number(value: object) -> float | None:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ return float(value)
+
+
+def _credits_to_usd(credits: object) -> float | None:
+ value = _optional_number(credits)
+ return None if value is None else round(value * _USD_PER_CREDIT, 2)
+
+
+def _optional_integer(value: object) -> int | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float) and value.is_integer():
+ return int(value)
+ return None
+
+
+def _desktop_usage_breakdown(limited: dict[str, Any]) -> dict[str, int | None] | None:
+ components = {
+ key: _optional_integer((limited.get(resource) or {}).get("usage"))
+ for key, resource in _DESKTOP_COMPONENT_RESOURCES.items()
+ }
+ return None if all(value is None for value in components.values()) else components
+
@extend_schema(tags=["tasks"])
class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@@ -63,3 +197,143 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
}
).data
)
+
+ # App-only credential endpoint, so it stays out of generated clients and MCP tools.
+ @extend_schema(exclude=True)
+ @action(detail=False, methods=["post"], url_path="gateway_token", required_scopes=["llm_gateway:read"])
+ def gateway_token(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Mints a `phe_` pinned to this team, the user and the plan's models. Any non-201 keeps the
+ app on the legacy gateway."""
+ access_token, refusal = _desktop_oauth_credential(request)
+ if refusal is not None or access_token is None:
+ return refusal or _disabled("oauth_required", status.HTTP_403_FORBIDDEN)
+ if not DesktopGatewayTokenThrottle().allow_request(request, self):
+ return _disabled(
+ "throttled", status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many gateway token requests. Try later."
+ )
+ user = cast(User, request.user)
+ team = self.team
+ organization = self.organization
+
+ if email_verification_pending(user):
+ return _disabled("email_unverified", status.HTTP_403_FORBIDDEN, detail="Verify your email to continue.")
+ # scoped_teams is frozen at consent, so re-check membership and project access.
+ if not oauth_credential_authorized(access_token, team):
+ return _disabled(
+ "unauthorized",
+ status.HTTP_403_FORBIDDEN,
+ detail="This credential is no longer authorized for this project.",
+ )
+ if not user.distinct_id:
+ return _disabled("oauth_required", status.HTTP_403_FORBIDDEN, detail="This account has no identity.")
+ distinct_id = str(user.distinct_id)
+ if wizard_identity_blocked(
+ distinct_id=distinct_id,
+ email=user.email,
+ user_uuid=str(user.uuid),
+ organization_ids=[str(organization.id)],
+ team_ids=[team.id],
+ surface="desktop_gateway_token",
+ ):
+ return _disabled("blocked", status.HTTP_403_FORBIDDEN, detail="This account cannot use the AI gateway.")
+
+ if not desktop_gateway_configured():
+ return _disabled("unconfigured")
+ if not desktop_rollout_enabled(organization, team, distinct_id):
+ return _disabled("not_rolled_out")
+
+ try:
+ # Cache funding for one token lifetime: the app re-mints that often, so staleness stays within a token.
+ decision = get_desktop_access_decision(
+ user, organization, funding_cache_seconds=desktop_token_ttl_seconds()
+ )
+ except DesktopAccessResolutionError:
+ return _disabled(
+ "desktop_access_unavailable",
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="We couldn't verify PostHog Desktop access. Try again.",
+ )
+ if not decision.allowed:
+ access_reason = decision.reason.value if decision.reason is not None else None
+ return _disabled(
+ "desktop_access_blocked",
+ status.HTTP_403_FORBIDDEN,
+ access={"allowed": False, "reason": access_reason},
+ detail=_DESKTOP_ACCESS_MESSAGES.get(access_reason or "", "PostHog Desktop access is required."),
+ )
+
+ try:
+ credit_refusal = team_credit_refusal(team.id, "posthog_code_credits")
+ except Exception as e:
+ capture_exception(e, {"ai_product": POSTHOG_CODE_PRODUCT, "team_id": team.id})
+ return _disabled("credit_state_unknown")
+ if credit_refusal == "org_deactivated":
+ return compute_quota_limit_response(ComputeQuotaDenialReason.ORGANIZATION_DEACTIVATED)
+ if credit_refusal is not None:
+ response = _disabled(
+ "credit_bucket_exhausted",
+ status.HTTP_402_PAYMENT_REQUIRED,
+ detail=POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL,
+ )
+ response["X-PostHog-Denial"] = CREDIT_BUCKET_EXHAUSTED_DENIAL
+ return response
+
+ plan = posthog_code_plan(team)
+ allowed_models = plan_allowed_models(plan)
+ try:
+ minted = mint_desktop_gateway_token(team_id=team.id, user=distinct_id, allowed_models=allowed_models)
+ except DesktopGatewayMintError as e:
+ if e.rate_limited:
+ # The shared mint ceiling is counted and logged at the mint, so skip the per-session capture.
+ return _disabled(
+ "mint_failed", status.HTTP_503_SERVICE_UNAVAILABLE, detail="Gateway token mint failed."
+ )
+ with posthoganalytics.new_context():
+ posthoganalytics.set_capture_exception_code_variables_context(False)
+ capture_exception(e, {"ai_product": POSTHOG_CODE_PRODUCT, "team_id": team.id})
+ return _disabled("mint_failed", status.HTTP_503_SERVICE_UNAVAILABLE, detail="Gateway token mint failed.")
+
+ echoed_models = minted.get("allowed_models")
+ payload = {
+ "enabled": True,
+ "token": minted["token"],
+ "expires_at": minted["expires_at"],
+ "cap_usd": minted.get("cap_usd"),
+ "gateway_url": desktop_gateway_base_url(),
+ "product": POSTHOG_CODE_PRODUCT,
+ "team_id": team.id,
+ "plan": plan,
+ # Go echoes only the pin it stored; a gateway without the echo stored what was sent.
+ "allowed_models": echoed_models if isinstance(echoed_models, list) else allowed_models,
+ "product_models": list(DESKTOP_AGENT_MODELS),
+ }
+ return Response(DesktopGatewayTokenSerializer(payload).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(exclude=True)
+ @action(detail=False, methods=["get"], url_path="usage", required_scopes=["llm_gateway:read"])
+ def usage(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """The legacy gateway's `/v1/usage/posthog_code` body, from Django's own quota state."""
+ snapshot = team_quota_snapshot(self.team)
+ limited = snapshot["limited"]
+ bucket = limited.get("posthog_code_credits") or {}
+ exhausted = bool(bucket.get("limited"))
+ now = timezone.now()
+ period = self.organization.current_billing_period
+ payload = {
+ "product": POSTHOG_CODE_PRODUCT,
+ "user_id": request.user.pk,
+ "burst": _exempt_window(now, _BURST_WINDOW_SECONDS),
+ "sustained": _exempt_window(now, _SUSTAINED_WINDOW_SECONDS),
+ "ai_credits": {
+ "exhausted": exhausted,
+ "used_usd": _credits_to_usd(bucket.get("usage")),
+ "limit_usd": _credits_to_usd(bucket.get("limit")),
+ "breakdown": _desktop_usage_breakdown(limited),
+ },
+ "is_rate_limited": exhausted,
+ # Older app builds require the field; no caller holds a Pro seat.
+ "is_pro": False,
+ "code_usage_subscribed": bool(snapshot["code_usage_billing_active"]),
+ "billing_period_end": _iso(period.end) if period is not None else None,
+ }
+ return Response(DesktopUsageSerializer(payload).data)
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
index 5ca543d246d4..cba8b510d02f 100644
--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
@@ -8,22 +8,37 @@ only when the product is allowlisted AND a token is present, so a mint failure o
disagreement degrades the run to the Python gateway rather than failing it.
"""
-import json
import time
import random
import logging
-from decimal import Decimal, InvalidOperation
-from typing import Any
+from typing import TYPE_CHECKING, Any
from django.conf import settings
import requests
from prometheus_client import Counter
-from products.tasks.backend.logic.services.gateway_model_pin import PRODUCT_ALLOWED_MODELS, model_allowed_by_product_pin
+from products.tasks.backend.logic.services.desktop_gateway_token import (
+ POSTHOG_CODE_PRODUCT,
+ PRODUCT_CREDIT_BUCKET,
+ _cap_override,
+ _team_credit_refusal,
+ _valid_cap,
+ desktop_rollout_enabled,
+ posthog_code_plan,
+ valid_caps,
+)
+from products.tasks.backend.logic.services.gateway_model_pin import (
+ FREE_TIER_MODELS,
+ PRODUCT_ALLOWED_MODELS,
+ model_allowed_by_product_pin,
+)
from products.tasks.backend.logic.services.run_actor import is_slack_interaction_state
from products.tasks.backend.logic.services.sandbox_config import MAX_SANDBOX_TTL_SECONDS
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+
logger = logging.getLogger(__name__)
AI_GATEWAY_TOKEN_MINTS = Counter(
@@ -53,9 +68,6 @@ _SIGNALS_STAGE_PRODUCTS = frozenset(
)
_SCOUT_STAGE_PREFIX = "scout:"
-_MAX_CAP_USD = Decimal("10000")
-_MAX_CAP_DECIMAL_PLACES = 6
-
# Products whose runs may mint an internally funded token. Mint scope needs
# server-side provenance: `internal` and some origin_product values are
# API-settable, so an unmapped origin marked internal resolves to
@@ -65,14 +77,17 @@ _MAX_CAP_DECIMAL_PLACES = 6
# `signals_inbox`, so the per-run cap and the product's daily budget bound those two.
# review_hog qualifies because validate_origin_product reserves the origin and
# the resolver requires the server-stamped `internal` flag; rows predating the
-# reservation resolve to posthog_code and cannot mint. slack_app needs server
+# reservation resolve to posthog_code and mint under its gates. slack_app needs server
# provenance too (has_slack_provenance), older rows included.
# workflows qualifies because validate_origin_product reserves its origin for the
# workflow_tasks endpoint. posthog_ai is API-settable but not internally funded: its token
# bills the run's own team to AI credits, and the mint refuses an exhausted balance.
+# posthog_code is the customer's own product: the token bills the run's team, and the rollout
+# flag, the plan pin and the credit bucket gate the mint.
MINTABLE_PRODUCTS = frozenset(
{
"posthog_ai",
+ "posthog_code",
"review_hog",
"slack_app",
"signals_scout",
@@ -91,12 +106,11 @@ MINTABLE_PRODUCTS = frozenset(
# ceiling. Mirrors the stages `Task.create_run` stamps.
INTERACTIVE_MINTABLE_PRODUCTS = frozenset({"signals_inbox", "signals_chat"})
-# Interactive runs with no wall-clock cap; their tokens last the sandbox lifetime.
-SANDBOX_BOUND_MINTABLE_PRODUCTS = frozenset({"posthog_ai", "slack_app"})
+# Interactive and user runs with no wall-clock cap; their tokens last the sandbox lifetime, and
+# each new sandbox mints its own token.
+SANDBOX_BOUND_MINTABLE_PRODUCTS = frozenset({"posthog_ai", "slack_app", "posthog_code"})
-# The Python gateway bills these mintable products to AI credits and stops them at zero.
-# The Go gateway has no credit check, so the mint checks the balance when the run starts.
-AI_CREDITS_BILLED_PRODUCTS = frozenset({"posthog_ai", "slack_app", "workflows"})
+AI_CREDITS_BILLED_PRODUCTS = frozenset(p for p, bucket in PRODUCT_CREDIT_BUCKET.items() if bucket == "ai_credits")
_PRODUCT_ALLOWED_MODELS = PRODUCT_ALLOWED_MODELS
@@ -154,6 +168,36 @@ def has_slack_provenance(
return is_slack_interaction_state(state) or internal or prior_slack_run
+def model_allowed_by_pin(pin: list[str], model: str | None) -> bool:
+ from products.tasks.backend.model_catalog import normalize_model_id # noqa: PLC0415
+
+ return bool(model) and normalize_model_id(model or "") in {normalize_model_id(entry) for entry in pin}
+
+
+def _posthog_code_team(team_id: int) -> "Team | None":
+ from posthog.models import Team # noqa: PLC0415
+
+ return Team.objects.select_related("organization").filter(id=team_id).first()
+
+
+def _posthog_code_refusal(team_id: int, model: str | None) -> str | None:
+ """The rollout flag is the switch for the product; a free plan's pin has no model an
+ unpinned or paid-model run could fall back to."""
+ team = _posthog_code_team(team_id)
+ if team is None or not desktop_rollout_enabled(team.organization, team):
+ return "not_rolled_out"
+ if posthog_code_plan(team) == "free" and not model_allowed_by_pin(FREE_TIER_MODELS, model):
+ return "model_outside_pin"
+ return None
+
+
+def posthog_code_allowed_models(team_id: int) -> list[str] | None:
+ team = _posthog_code_team(team_id)
+ if team is not None and posthog_code_plan(team) == "free":
+ return list(FREE_TIER_MODELS)
+ return None
+
+
def mint_refusal(
ai_product: str,
*,
@@ -169,38 +213,29 @@ def mint_refusal(
state, internal=internal, prior_slack_run=prior_slack_run
):
return "no_slack_provenance"
+ if ai_product == POSTHOG_CODE_PRODUCT:
+ refusal = _posthog_code_refusal(team_id, model)
+ if refusal:
+ return refusal
# The Pi harness reads only LLM_GATEWAY_URL.
if runtime == "pi":
return "pi_runtime"
# The gateway denies an off-pin model with no fallback.
if not model_allowed_by_product_pin(ai_product, model):
return "model_outside_pin"
- if ai_product not in AI_CREDITS_BILLED_PRODUCTS:
+ bucket = PRODUCT_CREDIT_BUCKET.get(ai_product)
+ if bucket is None:
return None
# An unknown balance is no licence to spend.
try:
- over_budget = _team_over_ai_credit_budget(team_id)
+ return _team_credit_refusal(team_id, bucket)
except Exception:
logger.warning(
- "ai_gateway_token: ai credit lookup failed, run stays on the Python gateway",
- extra={"team_id": team_id},
+ "ai_gateway_token: credit lookup failed, run stays on the Python gateway",
+ extra={"team_id": team_id, "bucket": bucket},
exc_info=True,
)
- return "ai_credits_unknown"
- if over_budget:
- return "ai_credits_exhausted"
- return None
-
-
-def _team_over_ai_credit_budget(team_id: int) -> bool:
- from posthog.models import Team # noqa: PLC0415
-
- from ee.billing.quota_limiting import is_team_over_ai_credit_budget # noqa: PLC0415
-
- api_token = Team.objects.filter(id=team_id).values_list("api_token", flat=True).first()
- if not api_token:
- return False
- return is_team_over_ai_credit_budget(api_token)
+ return f"{bucket}_unknown"
def _token_ttl_seconds(ai_product: str) -> int:
@@ -225,35 +260,6 @@ def _token_ttl_seconds(ai_product: str) -> int:
return max(60, min(configured, 86400))
-def _cap_override(raw: str, key: str, setting_name: str) -> str | None:
- if not raw:
- return None
- try:
- override = json.loads(raw).get(key)
- except (ValueError, AttributeError):
- logger.warning("Ignoring invalid JSON object for %s", setting_name)
- return None
- if override is None:
- return None
- try:
- cap = Decimal(str(override))
- except (InvalidOperation, ValueError):
- logger.warning("Ignoring invalid cap for %s", setting_name)
- return None
- if not cap.is_finite():
- logger.warning("Ignoring invalid cap for %s", setting_name)
- return None
- exponent = cap.as_tuple().exponent
- if not isinstance(exponent, int):
- logger.warning("Ignoring invalid cap for %s", setting_name)
- return None
- decimal_places = max(0, -exponent)
- if cap <= 0 or cap > _MAX_CAP_USD or decimal_places > _MAX_CAP_DECIMAL_PLACES:
- logger.warning("Ignoring invalid cap for %s", setting_name)
- return None
- return f"{cap:f}"
-
-
def token_cap_usd(team_id: int, ai_product: str) -> str:
"""Per-run cap: the product override, else the team override, else the default.
@@ -262,9 +268,14 @@ def token_cap_usd(team_id: int, ai_product: str) -> str:
team override raises a single team (team 2's custom scouts run hotter than
the external fleet) without raising everyone's ceiling.
"""
- product_cap = _cap_override(
- settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES, ai_product, "product cap overrides"
+ # An invalid env entry is dropped and reported, so the product keeps its code default.
+ product_cap = valid_caps(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES, "product cap overrides").get(
+ ai_product
)
+ if product_cap is None and ai_product in settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_DEFAULTS:
+ product_cap = _valid_cap(
+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_DEFAULTS[ai_product], "product cap defaults"
+ )
if product_cap is not None:
return product_cap
team_cap = _cap_override(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES, str(team_id), "cap overrides")
@@ -273,11 +284,14 @@ def token_cap_usd(team_id: int, ai_product: str) -> str:
return str(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD)
-def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None) -> str | None:
+def mint_scoped_token(
+ *, ai_product: str, team_id: int, user: str | None = None, allowed_models: list[str] | None = None
+) -> str | None:
"""Mint a `phe_` scoped token pinned to (ai_product, obo=team_id), or None on failure.
`user` pins the acting identity (the run's distinct id) so routed runs keep
per-user ledger and budget attribution instead of pooling under the team.
+ `allowed_models` narrows the product's pin (a free Desktop plan).
Retries mint rate limits (429) and transient upstream errors with jittered
backoff. Callers treat None as "route this run to the Python gateway".
"""
@@ -294,9 +308,9 @@ def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None)
}
if user:
body["user"] = user
- allowed_models = _PRODUCT_ALLOWED_MODELS.get(ai_product)
- if allowed_models:
- body["allowed_models"] = allowed_models
+ pin = allowed_models if allowed_models is not None else _PRODUCT_ALLOWED_MODELS.get(ai_product)
+ if pin:
+ body["allowed_models"] = pin
last_error: str = ""
for attempt in range(_MINT_ATTEMPTS):
try:
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.py
index 663c720535cf..c927f5eaf8b8 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
@@ -6,16 +6,27 @@ from pathlib import Path
from typing import TYPE_CHECKING
import pytest
+import time_machine
from unittest.mock import MagicMock, patch
from django.db import OperationalError
+from posthog.constants import AvailableFeature
from posthog.models import Organization, Team
from products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGE
from products.tasks.backend import model_catalog
from products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
from products.tasks.backend.facade.billing import get_task_run_cost
+from products.tasks.backend.logic.services.desktop_gateway_token import valid_caps
+from products.tasks.backend.logic.services.gateway_model_pin import (
+ DESKTOP_AGENT_MODELS,
+ FREE_TIER_MODELS,
+ FREE_TIER_PIN_KEY,
+ MAX_GATEWAY_PIN_LENGTH,
+ SDK_IMPLICIT_MODELS,
+ pinned_run_allows_model,
+)
from products.tasks.backend.logic.services.sandbox_config import MAX_SANDBOX_TTL_SECONDS
from products.tasks.backend.models import INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN
from products.tasks.backend.temporal.process_task import utils
@@ -24,11 +35,14 @@ from products.tasks.backend.temporal.process_task.ai_gateway_token import (
AI_CREDITS_BILLED_PRODUCTS,
INTERACTIVE_MINTABLE_PRODUCTS,
MINTABLE_PRODUCTS,
- _team_over_ai_credit_budget,
+ PRODUCT_CREDIT_BUCKET,
+ SANDBOX_BOUND_MINTABLE_PRODUCTS,
+ _team_credit_refusal,
mint_refusal,
mint_scoped_token,
resolve_sandbox_ai_product,
sandbox_product_routed,
+ token_cap_usd,
)
from products.tasks.backend.temporal.process_task.utils import ai_gateway_env_vars
@@ -287,6 +301,7 @@ class TestMintScopedToken:
class TestAiGatewayEnvVars:
+ @time_machine.travel("2026-09-23T12:00:00Z", tick=False)
def test_routed_run_gets_url_products_and_token(self, mint_settings):
with patch(
"products.tasks.backend.temporal.process_task.utils.mint_scoped_token",
@@ -319,8 +334,8 @@ class TestAiGatewayEnvVars:
return_value="phe_abc",
) as mint,
patch(
- "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
- return_value=False,
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal",
+ return_value=None,
),
):
env = ai_gateway_env_vars(team_id=123, origin_product="workflow")
@@ -729,15 +744,17 @@ class TestUserPinAndCapOverride:
assert post.call_args_list[1].kwargs["json"]["cap_usd"] == "10"
@pytest.mark.parametrize("invalid_product_cap", ["", True, 0, -1, "0.0000001", "10000.000001", "NaN"])
- def test_invalid_product_cap_falls_back_to_team_override(self, mint_settings, invalid_product_cap):
+ def test_invalid_product_cap_keeps_the_product_default(self, mint_settings, invalid_product_cap):
mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = '{"2": "10"}'
mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = json.dumps(
- {"signals_implementation": invalid_product_cap}
+ {"signals_implementation": invalid_product_cap, "signals_scout": invalid_product_cap}
)
with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
post.return_value = self._response({"token": "phe_abc"})
mint_scoped_token(ai_product="signals_implementation", team_id=2)
- assert post.call_args.kwargs["json"]["cap_usd"] == "10"
+ mint_scoped_token(ai_product="signals_scout", team_id=2)
+ # The code default for a product that has one, else the team override.
+ assert [c.kwargs["json"]["cap_usd"] for c in post.call_args_list] == ["20", "10"]
@pytest.mark.parametrize(
"ai_product,expected_cap",
@@ -748,6 +765,7 @@ class TestUserPinAndCapOverride:
("slack_app", "75"),
("workflows", "75"),
("posthog_ai", "75"),
+ ("posthog_code", "500"),
("signals_scout_suggestions", "10"),
],
)
@@ -788,8 +806,8 @@ class TestSlackAppMint:
"products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"
) as mint,
patch(
- "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
- return_value=over_quota,
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal",
+ return_value=("ai_credits_exhausted" if over_quota else None),
),
):
env = ai_gateway_env_vars(**kwargs)
@@ -839,7 +857,7 @@ class TestSlackAppMint:
with (
patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,
patch(
- "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal",
side_effect=RuntimeError("billing is down"),
),
):
@@ -855,7 +873,7 @@ class TestSlackAppMint:
def test_credit_lookup_failure_names_its_own_refusal(self):
with patch(
- "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal",
side_effect=RuntimeError("billing is down"),
):
refusal = mint_refusal(
@@ -943,13 +961,26 @@ class TestSlackAppMint:
assert _task_has_stamped_slack_run(other, "slack", unstamped) is False
@pytest.mark.django_db
- def test_quota_check_reads_the_team_token(self):
+ def test_quota_check_reads_the_team_token_and_bucket(self):
+ from ee.billing.quota_limiting import QuotaResource
+
organization = Organization.objects.create(name="Quota Org")
team = Team.objects.create(organization=organization, name="Quota Team")
- with patch("ee.billing.quota_limiting.is_team_over_ai_credit_budget", return_value=True) as quota:
- assert _team_over_ai_credit_budget(team.id) is True
- assert _team_over_ai_credit_budget(team.id + 10_000) is False
- quota.assert_called_once_with(team.api_token)
+ with patch("ee.billing.quota_limiting.is_team_over_credit_budget", return_value=True) as quota:
+ assert _team_credit_refusal(team.id, "ai_credits") == "ai_credits_exhausted"
+ assert _team_credit_refusal(team.id + 10_000, "ai_credits") is None
+ quota.assert_called_once_with(team.api_token, QuotaResource.AI_CREDITS)
+ with patch("ee.billing.quota_limiting.is_team_over_credit_budget", return_value=False) as quota:
+ assert _team_credit_refusal(team.id, "posthog_code_credits") is None
+ quota.assert_called_once_with(team.api_token, QuotaResource.POSTHOG_CODE_CREDITS)
+
+ @pytest.mark.django_db
+ def test_deactivated_org_refuses_before_the_bucket_is_read(self):
+ organization = Organization.objects.create(name="Gone Org", is_active=False)
+ team = Team.objects.create(organization=organization, name="Gone Team")
+ with patch("ee.billing.quota_limiting.is_team_over_credit_budget") as quota:
+ assert _team_credit_refusal(team.id, "ai_credits") == "org_deactivated"
+ quota.assert_not_called()
def test_mint_carries_the_first_party_pin(self, mint_settings):
with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
@@ -973,7 +1004,9 @@ class TestSlackAppMint:
assert post.call_args.kwargs["json"]["ttl_seconds"] == MAX_SANDBOX_TTL_SECONDS + 3600
-_CREDIT_LOOKUP = "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget"
+_CREDIT_LOOKUP = "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal"
+_POSTHOG_CODE_GATE = "products.tasks.backend.temporal.process_task.ai_gateway_token._posthog_code_refusal"
+_ROLLOUT = "products.tasks.backend.temporal.process_task.ai_gateway_token.desktop_rollout_enabled"
class TestMintRefusalScope:
@@ -981,9 +1014,41 @@ class TestMintRefusalScope:
assert AI_CREDITS_BILLED_PRODUCTS == {"posthog_ai", "slack_app", "workflows"}
assert AI_CREDITS_BILLED_PRODUCTS <= MINTABLE_PRODUCTS
+ def test_product_credit_buckets_are_quota_resources(self):
+ from ee.billing.quota_limiting import QuotaResource
+
+ assert PRODUCT_CREDIT_BUCKET == {
+ "posthog_ai": "ai_credits",
+ "posthog_code": "posthog_code_credits",
+ "slack_app": "ai_credits",
+ "workflows": "ai_credits",
+ }
+ assert set(PRODUCT_CREDIT_BUCKET.values()) == {
+ QuotaResource.AI_CREDITS.value,
+ QuotaResource.POSTHOG_CODE_CREDITS.value,
+ }
+
+ def test_posthog_code_refuses_on_its_own_bucket(self):
+ with (
+ patch(_POSTHOG_CODE_GATE, return_value=None),
+ patch(_CREDIT_LOOKUP, return_value="posthog_code_credits_exhausted") as quota,
+ ):
+ refusal = mint_refusal("posthog_code", team_id=2, state=None, model=None, runtime="acp")
+ assert refusal == "posthog_code_credits_exhausted"
+ quota.assert_called_once_with(2, "posthog_code_credits")
+
+ def test_lookup_failure_names_the_bucket(self):
+ with patch(_POSTHOG_CODE_GATE, return_value=None), patch(_CREDIT_LOOKUP, side_effect=RuntimeError("down")):
+ refusal = mint_refusal("posthog_code", team_id=2, state=None, model=None, runtime="acp")
+ assert refusal == "posthog_code_credits_unknown"
+
+ def test_deactivated_org_does_not_mint(self):
+ with patch(_CREDIT_LOOKUP, return_value="org_deactivated"):
+ assert mint_refusal("workflows", team_id=2, state=None, model=None, runtime="acp") == "org_deactivated"
+
@pytest.mark.parametrize("product", ["workflows", "review_hog", "signals_scout"])
def test_slack_provenance_gate_leaves_other_products_alone(self, product):
- with patch(_CREDIT_LOOKUP, return_value=False):
+ with patch(_CREDIT_LOOKUP, return_value=None):
assert mint_refusal(product, team_id=2, state=None, model=None, runtime="acp") is None
@pytest.mark.parametrize("product", ["workflows", "review_hog", "signals_scout"])
@@ -1000,7 +1065,7 @@ class TestMintRefusalScope:
@pytest.mark.parametrize("product", ["review_hog", "signals_scout", "signals_implementation"])
def test_products_billed_elsewhere_skip_the_credit_check(self, product):
- with patch(_CREDIT_LOOKUP, return_value=True) as quota:
+ with patch(_CREDIT_LOOKUP, return_value="ai_credits_exhausted") as quota:
assert mint_refusal(product, team_id=2, state=None, model=None, runtime="acp") is None
quota.assert_not_called()
@@ -1020,7 +1085,7 @@ class TestWorkflowsMint:
patch(
"products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"
) as mint,
- patch(_CREDIT_LOOKUP, return_value=over_quota),
+ patch(_CREDIT_LOOKUP, return_value=("ai_credits_exhausted" if over_quota else None)),
):
env = ai_gateway_env_vars(**kwargs)
return env, mint
@@ -1086,7 +1151,7 @@ class TestPosthogAiMint:
patch(
"products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"
) as mint,
- patch(_CREDIT_LOOKUP, return_value=over_quota),
+ patch(_CREDIT_LOOKUP, return_value="ai_credits_exhausted" if over_quota else None),
):
env = ai_gateway_env_vars(**kwargs)
return env, mint
@@ -1132,3 +1197,216 @@ class TestPosthogAiMint:
post.return_value = response
mint_scoped_token(ai_product="posthog_ai", team_id=2)
assert post.call_args.kwargs["json"]["ttl_seconds"] == MAX_SANDBOX_TTL_SECONDS + 3600
+
+
+class TestPosthogCodeSandboxMint:
+ def _team(self, *, paid: bool) -> Team:
+ organization = Organization.objects.create(name="Code Org")
+ if paid:
+ organization.available_product_features = [
+ {"key": AvailableFeature.POSTHOG_CODE_USAGE, "name": "PostHog Desktop usage billing"}
+ ]
+ organization.save()
+ return Team.objects.create(organization=organization, name="Code Team")
+
+ def _mint_response(self, token="phe_abc", expires_at="2026-09-24T12:00:00Z"):
+ return MagicMock(status_code=201, json=MagicMock(return_value={"token": token, "expires_at": expires_at}))
+
+ def test_posthog_code_is_mintable_and_sandbox_bound(self):
+ assert "posthog_code" in MINTABLE_PRODUCTS
+ assert "posthog_code" in SANDBOX_BOUND_MINTABLE_PRODUCTS
+
+ def test_pin_holds_every_catalog_id_and_fits_the_gateway(self):
+ pin = _PRODUCT_ALLOWED_MODELS["posthog_code"]
+ assert pin == DESKTOP_AGENT_MODELS
+ assert len(pin) == len(set(pin)) <= MAX_GATEWAY_PIN_LENGTH
+ assert {entry.id for entry in model_catalog.MODELS} <= set(pin)
+ assert set(SDK_IMPLICIT_MODELS) <= set(pin)
+ assert {"gpt-5.4", "gpt-5.3-codex", "gpt-5.2", "gpt-5-mini"} <= set(pin)
+ assert any("/" in model for model in pin)
+
+ def test_free_pin_is_the_three_open_weight_models(self):
+ assert FREE_TIER_MODELS == ["@cf/zai-org/glm-5.2", "deepseek-ai/deepseek-v4-flash-0731", "moonshotai/kimi-k3"]
+ assert _PRODUCT_ALLOWED_MODELS[FREE_TIER_PIN_KEY] == FREE_TIER_MODELS
+
+ def test_ttl_is_the_sandbox_lifetime_plus_an_hour(self, mint_settings):
+ # The sandbox dies at its TTL and a new one mints its own token, so a leaked token
+ # outlives its sandbox by the settle hour at most.
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0
+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60
+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
+ post.return_value = self._mint_response()
+ mint_scoped_token(ai_product="posthog_code", team_id=2)
+ assert post.call_args.kwargs["json"]["ttl_seconds"] == MAX_SANDBOX_TTL_SECONDS + 3600
+
+ def test_env_product_caps_merge_onto_the_defaults(self, mint_settings):
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = '{"posthog_ai": "90", "review_hog": "75"}'
+ caps = {product: token_cap_usd(2, product) for product in ("posthog_ai", "review_hog", "posthog_code")}
+ assert caps == {"posthog_ai": "90", "review_hog": "75", "posthog_code": "500"}
+
+ @pytest.mark.parametrize(
+ "raw",
+ ["{'posthog_code': '5'}", '["posthog_code"]', '{"posthog_code": "5", "posthog_ai": "not a number"}'],
+ )
+ def test_bad_product_caps_keep_the_defaults_and_are_captured_once(self, mint_settings, raw):
+ valid_caps.cache_clear()
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = raw
+ with patch("products.tasks.backend.logic.services.desktop_gateway_token.capture_exception") as capture:
+ caps = [token_cap_usd(2, "posthog_ai") for _ in range(3)]
+ assert caps == ["75"] * 3
+ capture.assert_called_once()
+
+ def test_a_valid_entry_survives_an_invalid_sibling(self, mint_settings):
+ valid_caps.cache_clear()
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = (
+ '{"posthog_code": "450", "posthog_ai": "bad"}'
+ )
+ with patch("products.tasks.backend.logic.services.desktop_gateway_token.capture_exception"):
+ assert token_cap_usd(2, "posthog_code") == "450"
+ assert token_cap_usd(2, "posthog_ai") == "75"
+
+ def test_a_bad_cap_map_is_reported_without_code_variables(self, mint_settings):
+ valid_caps.cache_clear()
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = "not json"
+ module = "products.tasks.backend.logic.services.desktop_gateway_token"
+ with (
+ patch(f"{module}.capture_exception"),
+ patch(f"{module}.posthoganalytics.set_capture_exception_code_variables_context") as code_variables,
+ ):
+ token_cap_usd(2, "posthog_ai")
+ code_variables.assert_called_once_with(False)
+
+ def test_product_cap_beats_the_team_override(self, mint_settings):
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = '{"2": "10"}'
+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = '{"posthog_code": "500"}'
+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
+ post.return_value = self._mint_response()
+ mint_scoped_token(ai_product="posthog_code", team_id=2)
+ assert post.call_args.kwargs["json"]["cap_usd"] == "500"
+
+ def test_paid_mint_sends_the_desktop_pin_and_an_explicit_pin_replaces_it(self, mint_settings):
+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
+ post.return_value = self._mint_response()
+ mint_scoped_token(ai_product="posthog_code", team_id=2)
+ mint_scoped_token(ai_product="posthog_code", team_id=2, allowed_models=FREE_TIER_MODELS)
+ assert post.call_args_list[0].kwargs["json"]["allowed_models"] == DESKTOP_AGENT_MODELS
+ assert post.call_args_list[1].kwargs["json"]["allowed_models"] == FREE_TIER_MODELS
+
+ @pytest.mark.django_db
+ def test_flag_off_skips_as_not_rolled_out(self, mint_settings):
+ team = self._team(paid=True)
+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"
+ with (
+ patch(_ROLLOUT, return_value=False),
+ patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,
+ patch.object(utils, "logger") as log,
+ ):
+ env = ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model="claude-opus-5")
+ assert "AI_GATEWAY_TOKEN" not in env
+ mint.assert_not_called()
+ assert log.info.call_args.kwargs["extra"]["reason"] == "not_rolled_out"
+
+ @pytest.mark.django_db
+ def test_flag_outage_reads_as_off(self):
+ team = self._team(paid=True)
+ with patch(
+ "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",
+ side_effect=RuntimeError("flags down"),
+ ):
+ assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="acp") == (
+ "not_rolled_out"
+ )
+
+ @pytest.mark.django_db
+ def test_flag_is_evaluated_for_the_team_org(self):
+ team = self._team(paid=True)
+ with (
+ patch(
+ "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",
+ return_value=True,
+ ) as flag,
+ patch(_CREDIT_LOOKUP, return_value=None),
+ ):
+ assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="acp") is None
+ assert flag.call_args.args[0] == "posthog-desktop-ai-gateway"
+ assert flag.call_args.kwargs["groups"]["organization"] == str(team.organization_id)
+
+ @pytest.mark.django_db
+ def test_off_pin_model_refuses(self):
+ team = self._team(paid=True)
+ with patch(_ROLLOUT, return_value=True), patch(_CREDIT_LOOKUP, return_value=None):
+ refusal = mint_refusal("posthog_code", team_id=team.id, state=None, model="gpt-5.5-codex", runtime="acp")
+ assert refusal == "model_outside_pin"
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize("model", [None, "claude-opus-5", "zai-org/glm-5.3"])
+ def test_free_plan_refuses_a_model_outside_the_free_pin(self, model):
+ team = self._team(paid=False)
+ with patch(_ROLLOUT, return_value=True), patch(_CREDIT_LOOKUP, return_value=None):
+ refusal = mint_refusal("posthog_code", team_id=team.id, state=None, model=model, runtime="acp")
+ assert refusal == "model_outside_pin"
+
+ @pytest.mark.django_db
+ def test_free_plan_mints_the_free_pin_and_stamps_it(self, mint_settings):
+ team = self._team(paid=False)
+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"
+ with (
+ patch(_ROLLOUT, return_value=True),
+ patch(_CREDIT_LOOKUP, return_value=None),
+ patch(
+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"
+ ) as mint,
+ ):
+ env = ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model="@cf/zai-org/glm-5.2")
+ mint.assert_called_once_with(
+ ai_product="posthog_code", team_id=team.id, user=None, allowed_models=FREE_TIER_MODELS
+ )
+ assert env["AI_GATEWAY_PRODUCT"] == "posthog_code"
+ assert env[utils._PIN_KEY_ENV] == FREE_TIER_PIN_KEY
+
+ @pytest.mark.django_db
+ def test_paid_plan_mints_the_product_pin(self, mint_settings):
+ team = self._team(paid=True)
+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"
+ with (
+ patch(_ROLLOUT, return_value=True),
+ patch(_CREDIT_LOOKUP, return_value=None),
+ patch(
+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"
+ ) as mint,
+ ):
+ env = ai_gateway_env_vars(team_id=team.id, origin_product="loop", model="claude-opus-5")
+ mint.assert_called_once_with(ai_product="posthog_code", team_id=team.id, user=None)
+ assert env["AI_GATEWAY_TOKEN"] == "phe_abc"
+ assert utils._PIN_KEY_ENV not in env
+
+ def test_run_state_stamps_the_product_pin(self, mint_settings):
+ env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "posthog_code"}
+ with (
+ patch.object(utils, "ai_gateway_env_vars", return_value=env),
+ patch.object(utils, "record_gateway_routing") as routing,
+ patch("products.tasks.backend.models.TaskRun.update_state_atomic") as update,
+ ):
+ ctx = TestProvisioningBoundaries()._ctx()
+ utils.run_gateway_env_vars(ctx, TestProvisioningBoundaries()._task())
+ update.assert_called_once_with(ctx.run_id, updates={"ai_gateway_product": "posthog_code"})
+ assert routing.call_args.kwargs["uses_gateway"] is True
+
+ def test_free_run_stamps_the_free_pin_and_hides_the_marker(self, mint_settings):
+ env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "posthog_code", utils._PIN_KEY_ENV: FREE_TIER_PIN_KEY}
+ 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,
+ ):
+ ctx = TestProvisioningBoundaries()._ctx()
+ out = utils.run_gateway_env_vars(ctx, TestProvisioningBoundaries()._task())
+ update.assert_called_once_with(ctx.run_id, updates={"ai_gateway_product": FREE_TIER_PIN_KEY})
+ assert utils._PIN_KEY_ENV not in out
+ assert out["AI_GATEWAY_TOKEN"] == "phe"
+
+ def test_free_stamp_blocks_a_switch_to_a_paid_model(self):
+ state = {"ai_gateway_product": FREE_TIER_PIN_KEY}
+ assert pinned_run_allows_model(state, "moonshotai/kimi-k3")
+ assert not pinned_run_allows_model(state, "claude-opus-5")
+ assert pinned_run_allows_model({"ai_gateway_product": "posthog_code"}, "claude-opus-5")
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index c698e5082f90..89802d99e2a6 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -37,7 +37,11 @@ from products.tasks.backend.constants import (
from products.tasks.backend.exceptions import CredentialUnavailableError
from products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled
from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access
-from products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, PRODUCT_ALLOWED_MODELS
+from products.tasks.backend.logic.services.gateway_model_pin import (
+ FREE_TIER_PIN_KEY,
+ GATEWAY_PRODUCT_STATE_KEY,
+ PRODUCT_ALLOWED_MODELS,
+)
from products.tasks.backend.logic.services.gateway_usage import record_gateway_routing
from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS
from products.tasks.backend.logic.services.mcp_url import resolve_mcp_url as _resolve_mcp_url
@@ -55,9 +59,11 @@ from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.temporal.process_task.ai_gateway_token import (
AI_GATEWAY_TOKEN_MINTS,
MINTABLE_PRODUCTS,
+ POSTHOG_CODE_PRODUCT,
is_slack_origin,
mint_refusal,
mint_scoped_token,
+ posthog_code_allowed_models,
resolve_sandbox_ai_product,
sandbox_product_routed,
token_cap_usd,
@@ -1378,10 +1384,11 @@ 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")):
+ pinned = env_vars.pop(_PIN_KEY_ENV, None) or env_vars.get("AI_GATEWAY_PRODUCT")
+ if not _record_pinned_gateway_product(ctx.run_id, ctx.state, pinned):
# 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)
+ for key in _TOKEN_ENV_KEYS:
+ env_vars.pop(key, None)
except Exception:
# Degrading to the Python gateway beats failing the provisioning activity and the run.
AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()
@@ -1413,6 +1420,11 @@ def _task_has_stamped_slack_run(task, origin_product: str | None, state: dict |
return TaskRun.objects.filter(task_id=task.id, state__interaction_origin="slack").exists()
+_TOKEN_ENV_KEYS = ("AI_GATEWAY_TOKEN", "AI_GATEWAY_TOKEN_CAP_USD")
+# Carries a narrower pin than the product's own to the run stamp; popped before the env reaches the sandbox.
+_PIN_KEY_ENV = "_AI_GATEWAY_PIN_KEY"
+
+
def _record_pinned_gateway_product(run_id: str, state: dict | None, minted_product: str | None) -> bool:
"""Stamp the run with the pinned product of its token. False leaves a pinned run unstamped."""
from products.tasks.backend.models import TaskRun # noqa: PLC0415
@@ -1489,11 +1501,18 @@ def ai_gateway_env_vars(
extra={"ai_product": ai_product, "team_id": team_id, "reason": refusal},
)
return env_vars
- token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id)
+ mint_kwargs: dict[str, Any] = {}
+ if ai_product == POSTHOG_CODE_PRODUCT:
+ free_pin = posthog_code_allowed_models(team_id)
+ if free_pin is not None:
+ mint_kwargs["allowed_models"] = free_pin
+ token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id, **mint_kwargs)
if token:
env_vars["AI_GATEWAY_TOKEN"] = token
env_vars["AI_GATEWAY_TOKEN_CAP_USD"] = token_cap_usd(team_id, ai_product)
env_vars["AI_GATEWAY_PRODUCT"] = ai_product
+ if "allowed_models" in mint_kwargs:
+ env_vars[_PIN_KEY_ENV] = FREE_TIER_PIN_KEY
if ai_stage:
env_vars["AI_GATEWAY_AI_STAGE"] = ai_stage
return env_vars
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index d0b288887c10..979394e68f52 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -22,7 +22,6 @@ from django.test.utils import CaptureQueriesContext
from django.utils import timezone as django_timezone
import jwt
-import requests
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
@@ -52,7 +51,6 @@ from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskAr
from products.tasks.backend.logic.services.ai_run_defaults import update_team_ai_run_preferences
from products.tasks.backend.logic.services.code_usage_gate import (
CodeUsageStatus,
- _gateway_usage_url,
code_access_required_response,
get_posthog_code_usage,
usage_limit_response,
@@ -106,6 +104,8 @@ from products.tasks.backend.presentation.views import api as views_api
from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
+from ee.billing.quota_limiting import QuotaResource
+
# The catalog gates no model behind a rollout flag now, so the write paths that re-check
# entitlement are exercised with a stand-in rather than with whichever model is mid-rollout.
GATED_MODEL_FLAG = "tasks-test-model-gate"
@@ -15586,79 +15586,42 @@ class TestCloudUsageGate(BaseTaskAPITest):
class TestGetPosthogCodeUsage(TestCase):
- @override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
- def test_parses_rate_limited_usage(self, mock_token, mock_get):
- mock_token.return_value = "tok"
- mock_get.return_value = MagicMock(
- status_code=200,
- json=lambda: {
- "is_rate_limited": True,
- "burst": {"exceeded": True, "reset_at": "2026-06-09T00:00:00Z"},
- "sustained": {"exceeded": False, "reset_at": "2026-07-01T00:00:00Z"},
- "is_pro": True,
- },
- )
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Usage Org")
+ self.team = Team.objects.create(organization=self.organization, name="Usage Team")
- usage = get_posthog_code_usage(MagicMock(), 1)
+ @patch("ee.billing.quota_limiting.is_team_over_credit_budget", return_value=True)
+ def test_exhausted_bucket_is_rate_limited_until_the_period_end(self, mock_over):
+ self.organization.usage = {"period": ["2026-09-01T00:00:00Z", "2026-10-01T00:00:00Z"]}
+ self.organization.save()
- assert usage is not None
- self.assertTrue(usage.is_rate_limited)
- self.assertEqual(usage.limit_type, "burst")
- self.assertEqual(usage.reset_at, "2026-06-09T00:00:00Z")
- self.assertTrue(usage.is_pro)
- self.assertEqual(mock_get.call_args.args[0], "https://gateway.us.posthog.com/v1/usage/posthog_code")
-
- @override_settings(DEBUG=True, CLOUD_DEPLOYMENT=None)
- def test_local_uses_localhost_gateway(self):
- self.assertEqual(_gateway_usage_url(), "http://localhost:3308/v1/usage/posthog_code")
-
- @override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.logic.services.code_usage_gate.OAuthAccessToken")
- @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
- def test_token_cleanup_error_does_not_break_fail_open(self, mock_token, mock_get, mock_oauth_model):
- mock_token.return_value = "tok"
- mock_get.return_value = MagicMock(
- status_code=200,
- json=lambda: {
- "is_rate_limited": True,
- "burst": {"exceeded": True, "reset_at": "2026-06-09T00:00:00Z"},
- "sustained": {"exceeded": False, "reset_at": "2026-07-01T00:00:00Z"},
- "is_pro": False,
- },
+ usage = get_posthog_code_usage(self.team.id)
+
+ assert usage == CodeUsageStatus(
+ is_rate_limited=True, limit_type=None, reset_at="2026-10-01T00:00:00+00:00", is_pro=False
)
- mock_oauth_model.objects.filter.return_value.delete.side_effect = Exception("db down")
+ mock_over.assert_called_once_with(self.team.api_token, QuotaResource.POSTHOG_CODE_CREDITS)
- usage = get_posthog_code_usage(MagicMock(), 1)
+ @patch("ee.billing.quota_limiting.is_team_over_credit_budget", return_value=True)
+ def test_unknown_period_leaves_reset_unset(self, _mock_over):
+ usage = get_posthog_code_usage(self.team.id)
assert usage is not None
self.assertTrue(usage.is_rate_limited)
+ self.assertIsNone(usage.reset_at)
- @parameterized.expand(
- [
- ("non_200", 500, None),
- ("network_error", None, None),
- ]
- )
- @override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
- def test_fails_open_on_gateway_error(self, _name, status_code, _unused, mock_token, mock_get):
- mock_token.return_value = "tok"
- if status_code is None:
- mock_get.side_effect = requests.RequestException("boom")
- else:
- mock_get.return_value = MagicMock(status_code=status_code)
+ @patch("ee.billing.quota_limiting.is_team_over_credit_budget", return_value=False)
+ def test_open_bucket_is_not_rate_limited(self, _mock_over):
+ usage = get_posthog_code_usage(self.team.id)
+
+ assert usage == CodeUsageStatus(is_rate_limited=False, limit_type=None, reset_at=None, is_pro=False)
- self.assertIsNone(get_posthog_code_usage(MagicMock(), 1))
+ @patch("ee.billing.quota_limiting.is_team_over_credit_budget", side_effect=Exception("redis down"))
+ def test_fails_open_on_lookup_error(self, _mock_over):
+ self.assertIsNone(get_posthog_code_usage(self.team.id))
- @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="DEV")
- @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
- def test_fails_open_when_no_gateway_url(self, mock_token):
- self.assertIsNone(get_posthog_code_usage(MagicMock(), 1))
- mock_token.assert_not_called()
+ def test_fails_open_for_an_unknown_team(self):
+ self.assertIsNone(get_posthog_code_usage(self.team.id + 10_000))
class TestUsageLimitResponse(TestCase):
diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.py
index 6403568665fd..e9d38010f0e1 100644
--- a/products/tasks/backend/tests/test_desktop_access.py
+++ b/products/tasks/backend/tests/test_desktop_access.py
@@ -93,6 +93,84 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertTrue(decision.allowed)
mock_funding.assert_not_called()
+ @parameterized.expand(
+ [
+ ("allowed", None, PrepaidCreditState.NONE, True),
+ ("startup", "Startup", PrepaidCreditState.NONE, False),
+ ("prepaid", None, PrepaidCreditState.ACTIVE, False),
+ ]
+ )
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_funding_cache_reuses_the_decision_within_its_window(
+ self, _name, startup_program_label, prepaid_credit_state, expected_allowed, mock_funding
+ ) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label=startup_program_label, prepaid_credit_state=prepaid_credit_state
+ )
+ first = get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+ second = get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+
+ self.assertEqual((first.allowed, second.allowed), (expected_allowed, expected_allowed))
+ self.assertEqual(first, second)
+ self.assertEqual(mock_funding.call_count, 1)
+ # The per-user override flag is never cached.
+ self.assertEqual(self.mock_feature_flag.call_count, 2)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_funding_cache_lives_for_the_window_it_was_given(self, mock_funding) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE
+ )
+ with patch("products.tasks.backend.access.cache.set", wraps=cache.set) as cache_set:
+ get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+ cache_set.assert_called_once_with(
+ f"desktop_access_funding_decision:{self.organization.id}", "allowed", timeout=300
+ )
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_without_a_funding_cache_every_call_reads_funding(self, mock_funding) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE
+ )
+ get_desktop_access_decision(self.user, self.organization)
+ get_desktop_access_decision(self.user, self.organization)
+ self.assertEqual(mock_funding.call_count, 2)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_a_funding_failure_is_not_cached(self, mock_funding) -> None:
+ mock_funding.side_effect = [
+ DesktopAccessResolutionError("unavailable"),
+ OrganizationFundingStatus(startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE),
+ ]
+ with self.assertRaises(DesktopAccessResolutionError):
+ get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+ self.assertTrue(get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300).allowed)
+ self.assertEqual(mock_funding.call_count, 2)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_an_unexpected_cached_value_falls_through_to_the_live_lookup(self, mock_funding) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label="Startup", prepaid_credit_state=PrepaidCreditState.NONE
+ )
+ for unexpected in (["allowed"], "not_a_decision"):
+ cache.set(f"desktop_access_funding_decision:{self.organization.id}", unexpected, timeout=300)
+ decision = get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+ self.assertFalse(decision.allowed)
+ self.assertEqual(mock_funding.call_count, 2)
+
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_a_cache_error_falls_through_to_the_live_lookup(self, mock_funding) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label="Startup", prepaid_credit_state=PrepaidCreditState.NONE
+ )
+ with (
+ patch("products.tasks.backend.access.cache.get", side_effect=ConnectionError("down")),
+ patch("products.tasks.backend.access.cache.set", side_effect=ConnectionError("down")),
+ ):
+ decision = get_desktop_access_decision(self.user, self.organization, funding_cache_seconds=300)
+ self.assertFalse(decision.allowed)
+ mock_funding.assert_called_once()
+
@patch(
"products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",
side_effect=DesktopAccessResolutionError("unavailable"),
diff --git a/products/tasks/backend/tests/test_desktop_gateway_token.py b/products/tasks/backend/tests/test_desktop_gateway_token.py
new file mode 100644
index 000000000000..9c5e3fd13632
--- /dev/null
+++ b/products/tasks/backend/tests/test_desktop_gateway_token.py
@@ -0,0 +1,602 @@
+import uuid
+from datetime import timedelta
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import override_settings
+from django.utils import timezone
+
+import requests
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.constants import AvailableFeature
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
+
+from products.tasks.backend.access import DesktopAccessDecision, DesktopAccessResolutionError
+from products.tasks.backend.logic.services.desktop_gateway_token import DESKTOP_GATEWAY_MINTS
+from products.tasks.backend.logic.services.gateway_model_pin import DESKTOP_AGENT_MODELS, FREE_TIER_MODELS
+
+from ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState
+
+_VIEW = "products.tasks.backend.presentation.views.desktop_access"
+_POST = "products.tasks.backend.logic.services.desktop_gateway_token.requests.post"
+_EXHAUSTED = (
+ "Your team has reached its PostHog Desktop usage limit for this billing period. "
+ "See https://app.posthog.com/organization/billing for your usage and limits."
+)
+
+GATEWAY_SETTINGS = {
+ "DESKTOP_GATEWAY_URL": "https://ai-gateway.test/v1",
+ "DESKTOP_GATEWAY_MINT_KEY": "phs_desktop",
+ "DESKTOP_GATEWAY_TOKEN_CAP_USD": "200",
+ "DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES": "",
+}
+
+
+def _response(status_code: int, body: object = None) -> MagicMock:
+ response = MagicMock(status_code=status_code)
+ response.json.return_value = body if body is not None else {}
+ return response
+
+
+def _minted(token: str = "phe_new", allowed_models: list[str] | None = None) -> MagicMock:
+ body: dict = {"token": token, "expires_at": "2099-01-01T00:00:00Z", "cap_usd": "200"}
+ if allowed_models is not None:
+ body["allowed_models"] = allowed_models
+ return _response(201, body)
+
+
+class _GatewayTestBase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ settings_override = override_settings(**GATEWAY_SETTINGS)
+ settings_override.enable()
+ self.addCleanup(settings_override.disable)
+ self.application = OAuthApplication.objects.create(
+ name="PostHog Desktop",
+ client_id=ARRAY_APP_CLIENT_ID_DEV,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ algorithm="RS256",
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ user=self.user,
+ )
+
+ def _oauth_token(self, *, scope: str = "llm_gateway:read", application=None, **fields) -> OAuthAccessToken:
+ return OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application or self.application,
+ token=f"pha_desktop_{uuid.uuid4().hex}",
+ expires=timezone.now() + timedelta(hours=1),
+ scope=scope,
+ scoped_teams=[self.team.id],
+ **fields,
+ )
+
+ def _client(self, **token_fields) -> APIClient:
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {self._oauth_token(**token_fields).token}")
+ return client
+
+ def _url(self, path: str) -> str:
+ return f"/api/projects/{self.team.id}/desktop/{path}/"
+
+
+class TestDesktopGatewayTokenMint(_GatewayTestBase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.gates = {
+ "rollout": patch(f"{_VIEW}.desktop_rollout_enabled", return_value=True),
+ "access": patch(f"{_VIEW}.get_desktop_access_decision", return_value=DesktopAccessDecision.ALLOWED),
+ "credit": patch(f"{_VIEW}.team_credit_refusal", return_value=None),
+ "blocked": patch(f"{_VIEW}.wizard_identity_blocked", return_value=False),
+ }
+ self.mocks = {name: patcher.start() for name, patcher in self.gates.items()}
+ for patcher in self.gates.values():
+ self.addCleanup(patcher.stop)
+
+ def _mint(self, client: APIClient | None = None, *, go=None, body: dict | None = None):
+ with patch(_POST) as post:
+ post.return_value = go if go is not None else _minted()
+ response = (client or self._client()).post(self._url("gateway_token"), body or {}, format="json")
+ return response, post
+
+ def test_session_auth_is_refused(self) -> None:
+ response, post = self._mint(self.client)
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json() == {
+ "enabled": False,
+ "reason": "oauth_required",
+ "detail": "Sign in with PostHog Desktop.",
+ }
+ post.assert_not_called()
+
+ def test_personal_api_key_is_refused(self) -> None:
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k", user=self.user, secure_value=hash_key_value(key), scopes=["llm_gateway:read"]
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")
+ response, post = self._mint(client)
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "oauth_required"
+ post.assert_not_called()
+
+ def test_other_oauth_app_is_refused(self) -> None:
+ other = OAuthApplication.objects.create(
+ name="Other",
+ client_id="other-client",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ algorithm="RS256",
+ redirect_uris="https://example.com/callback",
+ organization=self.organization,
+ user=self.user,
+ )
+ response, post = self._mint(self._client(application=other))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "oauth_required"
+ post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("wildcard_scope", {"scope": "*"}),
+ ("sandbox_scope", {"scope": "llm_gateway:read internal_run:read"}),
+ ("sandbox_binding", {"sandbox_task_id": uuid.uuid4()}),
+ ]
+ )
+ def test_non_interactive_credentials_are_refused(self, _name, fields) -> None:
+ response, post = self._mint(self._client(**fields))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "oauth_required"
+ post.assert_not_called()
+
+ def test_impersonation_token_is_refused(self) -> None:
+ staff = self._create_user("[email protected]")
+ response, post = self._mint(self._client(impersonated_by=staff))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "oauth_required"
+ post.assert_not_called()
+
+ def test_unverified_email_is_refused(self) -> None:
+ with patch(f"{_VIEW}.email_verification_pending", return_value=True):
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "email_unverified"
+ post.assert_not_called()
+
+ def test_credential_no_longer_authorized_is_refused(self) -> None:
+ with patch(f"{_VIEW}.oauth_credential_authorized", return_value=False):
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "unauthorized"
+ post.assert_not_called()
+
+ def test_blocklisted_identity_is_refused_before_the_flag(self) -> None:
+ self.mocks["blocked"].return_value = True
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["reason"] == "blocked"
+ self.mocks["rollout"].assert_not_called()
+ post.assert_not_called()
+ self.mocks["blocked"].assert_called_once_with(
+ distinct_id=str(self.user.distinct_id),
+ email=self.user.email,
+ user_uuid=str(self.user.uuid),
+ organization_ids=[str(self.organization.id)],
+ team_ids=[self.team.id],
+ surface="desktop_gateway_token",
+ )
+
+ @override_settings(DESKTOP_GATEWAY_MINT_KEY="")
+ def test_unconfigured_is_disabled(self) -> None:
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"enabled": False, "reason": "unconfigured"}
+ self.mocks["rollout"].assert_not_called()
+ post.assert_not_called()
+
+ def test_flag_off_is_not_rolled_out_before_access_and_billing(self) -> None:
+ self.mocks["rollout"].return_value = False
+ self.mocks["credit"].return_value = "posthog_code_credits_exhausted"
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"enabled": False, "reason": "not_rolled_out"}
+ self.mocks["access"].assert_not_called()
+ self.mocks["credit"].assert_not_called()
+ post.assert_not_called()
+
+ def test_flag_is_evaluated_for_the_org_and_user(self) -> None:
+ self._mint()
+ organization, team, distinct_id = self.mocks["rollout"].call_args.args
+ assert (organization.id, team.id, distinct_id) == (self.organization.id, self.team.id, self.user.distinct_id)
+
+ def test_blocked_desktop_access_is_refused_before_billing(self) -> None:
+ self.mocks["access"].return_value = DesktopAccessDecision.STARTUP_PLAN
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json() == {
+ "enabled": False,
+ "reason": "desktop_access_blocked",
+ "access": {"allowed": False, "reason": "startup_plan"},
+ "detail": "PostHog Desktop isn't available for Startup or YC program organizations.",
+ }
+ self.mocks["credit"].assert_not_called()
+ post.assert_not_called()
+
+ def test_access_resolution_failure_is_unavailable(self) -> None:
+ self.mocks["access"].side_effect = DesktopAccessResolutionError("billing down")
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert response.json()["reason"] == "desktop_access_unavailable"
+ post.assert_not_called()
+
+ def test_deactivated_org_answers_the_existing_429(self) -> None:
+ self.mocks["credit"].return_value = "org_deactivated"
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert response.json()["code"] == "organization_deactivated"
+ post.assert_not_called()
+
+ def test_deactivated_org_refuses_a_token_caller_before_the_view(self) -> None:
+ self.organization.is_active = False
+ self.organization.save()
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["code"] == "organization_deactivated"
+ post.assert_not_called()
+
+ def test_exhausted_bucket_is_402_with_the_legacy_sentence(self) -> None:
+ self.mocks["credit"].return_value = "posthog_code_credits_exhausted"
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert response.json() == {"enabled": False, "reason": "credit_bucket_exhausted", "detail": _EXHAUSTED}
+ assert response["X-PostHog-Denial"] == "credit_bucket_exhausted:posthog_code_credits"
+ self.mocks["credit"].assert_called_once_with(self.team.id, "posthog_code_credits")
+ post.assert_not_called()
+
+ def test_unknown_credit_state_is_disabled(self) -> None:
+ self.mocks["credit"].side_effect = RuntimeError("redis down")
+ with patch(f"{_VIEW}.capture_exception") as capture:
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"enabled": False, "reason": "credit_state_unknown"}
+ post.assert_not_called()
+ capture.assert_called_once()
+
+ def test_free_plan_mints_the_free_pin(self) -> None:
+ response, post = self._mint(go=_minted(allowed_models=FREE_TIER_MODELS[:2]))
+ assert response.status_code == status.HTTP_201_CREATED
+ assert post.call_args.args[0] == "https://ai-gateway.test/v1/tokens"
+ assert post.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_desktop"}
+ assert post.call_args.kwargs["timeout"] == 3
+ assert post.call_args.kwargs["json"] == {
+ "cap_usd": "200",
+ "ttl_seconds": 300,
+ "product": "posthog_code",
+ "obo": str(self.team.id),
+ "user": self.user.distinct_id,
+ "allowed_models": FREE_TIER_MODELS,
+ }
+ assert response.json() == {
+ "enabled": True,
+ "token": "phe_new",
+ "expires_at": "2099-01-01T00:00:00Z",
+ "cap_usd": "200",
+ "gateway_url": "https://ai-gateway.test",
+ "product": "posthog_code",
+ "team_id": self.team.id,
+ "plan": "free",
+ # Go's echo, not what was sent: a region without a host shrinks the pin.
+ "allowed_models": FREE_TIER_MODELS[:2],
+ "product_models": DESKTOP_AGENT_MODELS,
+ }
+
+ def test_paid_plan_mints_the_desktop_pin(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.POSTHOG_CODE_USAGE, "name": "PostHog Desktop usage billing"}
+ ]
+ self.organization.save()
+ response, post = self._mint(go=_minted(allowed_models=DESKTOP_AGENT_MODELS))
+ assert response.status_code == status.HTTP_201_CREATED
+ assert post.call_args.kwargs["json"]["allowed_models"] == DESKTOP_AGENT_MODELS
+ assert response.json()["plan"] == "paid"
+ assert response.json()["allowed_models"] == DESKTOP_AGENT_MODELS
+
+ def test_missing_echo_falls_back_to_the_sent_pin(self) -> None:
+ response, _ = self._mint()
+ assert response.json()["allowed_models"] == FREE_TIER_MODELS
+
+ def test_team_cap_override_applies(self) -> None:
+ with override_settings(DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES=f'{{"{self.team.id}": "350"}}'):
+ _, post = self._mint()
+ assert post.call_args.kwargs["json"]["cap_usd"] == "350"
+
+ @parameterized.expand([("below_floor", 5, 60), ("above_ceiling", 999999, 86400), ("in_range", 1800, 1800)])
+ def test_ttl_is_clamped(self, _name, configured, expected) -> None:
+ with override_settings(DESKTOP_GATEWAY_TOKEN_TTL_SECONDS=configured):
+ _, post = self._mint()
+ assert post.call_args.kwargs["json"]["ttl_seconds"] == expected
+
+ @parameterized.expand([("rate_limited", 429), ("upstream_error", 502), ("bad_request", 400)])
+ def test_gateway_refusal_is_503(self, _name, go_status) -> None:
+ response, _ = self._mint(go=_response(go_status, {"error": "no"}))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert response.json() == {"enabled": False, "reason": "mint_failed", "detail": "Gateway token mint failed."}
+
+ @parameterized.expand(
+ [
+ ("rate_limited", _response(429, {"error": "no"}), "rate_limited"),
+ ("upstream_error", _response(502, {"error": "no"}), "refused"),
+ ("bad_request", _response(400, {"error": "no"}), "refused"),
+ ("malformed", _response(201, {"token": "phe_x"}), "malformed"),
+ ("ok", _minted(), "ok"),
+ ]
+ )
+ def test_the_mint_counter_separates_the_gateway_ceiling(self, _name, go, outcome) -> None:
+ def count(label: str) -> float:
+ return DESKTOP_GATEWAY_MINTS.labels(outcome=label)._value.get()
+
+ before = {label: count(label) for label in ("ok", "rate_limited", "refused", "malformed", "unreachable")}
+ self._mint(go=go)
+ after = {label: count(label) for label in before}
+ assert {label: after[label] - before[label] for label in before} == {
+ label: (1 if label == outcome else 0) for label in before
+ }
+
+ @parameterized.expand([("configured", 900, 900), ("clamped", 5, 60)])
+ def test_the_mint_caches_the_funding_lookup_for_the_token_lifetime(self, _name, configured, expected) -> None:
+ with override_settings(DESKTOP_GATEWAY_TOKEN_TTL_SECONDS=configured):
+ self._mint()
+ self.mocks["access"].assert_called_once()
+ assert self.mocks["access"].call_args.kwargs == {"funding_cache_seconds": expected}
+
+ @parameterized.expand([("valid", "350", "350", 0), ("invalid", "lots", "200", 1)])
+ def test_the_default_cap_is_minted_and_only_an_invalid_one_is_reported(
+ self, _name, configured, minted, reports
+ ) -> None:
+ from products.tasks.backend.logic.services import desktop_gateway_token
+
+ desktop_gateway_token._valid_default_cap.cache_clear()
+ with (
+ override_settings(DESKTOP_GATEWAY_TOKEN_CAP_USD=configured),
+ patch.object(desktop_gateway_token, "capture_exception") as capture,
+ ):
+ caps = [self._mint()[1].call_args.kwargs["json"]["cap_usd"] for _ in range(3)]
+ assert caps == [minted] * 3
+ assert capture.call_count == reports
+
+ def test_a_gateway_429_is_not_captured_but_other_failures_are(self) -> None:
+ with patch(f"{_VIEW}.capture_exception") as capture:
+ limited, _ = self._mint(go=_response(429, {"error": "slow down"}))
+ failed, _ = self._mint(go=_response(502, {"error": "no"}))
+ assert (limited.status_code, failed.status_code) == (503, 503)
+ assert limited.json()["reason"] == failed.json()["reason"] == "mint_failed"
+ capture.assert_called_once()
+
+ def test_a_bare_gateway_host_mints_and_is_returned_without_v1(self) -> None:
+ with override_settings(DESKTOP_GATEWAY_URL="https://ai-gateway.us.posthog.com"):
+ response, post = self._mint()
+ assert response.status_code == status.HTTP_201_CREATED
+ assert post.call_args.args[0] == "https://ai-gateway.us.posthog.com/v1/tokens"
+ assert response.json()["gateway_url"] == "https://ai-gateway.us.posthog.com"
+
+ def test_a_second_mint_within_the_token_lifetime_skips_the_billing_call(self) -> None:
+ self.gates["access"].stop()
+ with (
+ patch("products.tasks.backend.access.get_feature_flag_or_none", return_value=False),
+ patch(
+ "products.tasks.backend.access._get_funding_status",
+ return_value=OrganizationFundingStatus(
+ startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE
+ ),
+ ) as funding,
+ ):
+ first, _ = self._mint()
+ second, _ = self._mint()
+ self.mocks["access"] = self.gates["access"].start()
+ assert (first.status_code, second.status_code) == (status.HTTP_201_CREATED, status.HTTP_201_CREATED)
+ funding.assert_called_once()
+
+ def test_transport_failure_is_503(self) -> None:
+ with patch(_POST, side_effect=requests.ReadTimeout("slow")):
+ response = self._client().post(self._url("gateway_token"))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ def test_an_instance_id_is_ignored(self) -> None:
+ for instance_id in ("laptop-1", "a:b", 7, ""):
+ response, post = self._mint(body={"instance_id": instance_id})
+ assert response.status_code == status.HTTP_201_CREATED
+ assert "instance_id" not in post.call_args.kwargs["json"]
+
+ def test_malformed_mint_response_is_503(self) -> None:
+ response, _ = self._mint(go=_response(201, {"token": "phe_x"}))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ def test_per_user_throttle_refuses_after_the_hourly_ceiling(self) -> None:
+ with override_settings(DESKTOP_GATEWAY_MINTS_PER_HOUR=2):
+ codes = [self._mint()[0].status_code for _ in range(3)]
+ third, post = self._mint()
+ assert codes == [201, 201, 429]
+ assert third.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert third.json() == {
+ "enabled": False,
+ "reason": "throttled",
+ "detail": "Too many gateway token requests. Try later.",
+ }
+ post.assert_not_called()
+
+ def test_the_default_ceiling_is_120_mints_an_hour(self) -> None:
+ codes = [self._mint()[0].status_code for _ in range(121)]
+ assert codes == [201] * 120 + [429]
+
+ def test_a_refused_request_spends_a_slot_and_the_throttle_runs_before_the_gates(self) -> None:
+ with (
+ override_settings(DESKTOP_GATEWAY_MINTS_PER_HOUR=1),
+ patch(f"{_VIEW}.oauth_credential_authorized", return_value=True) as authorized,
+ patch(f"{_VIEW}.email_verification_pending", return_value=False) as email_pending,
+ ):
+ self.mocks["credit"].return_value = "posthog_code_credits_exhausted"
+ refused, _ = self._mint()
+ self.mocks["credit"].return_value = None
+ throttled, post = self._mint()
+ assert refused.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ # The throttled request reached no gate past the credential shape check.
+ for gate in (email_pending, authorized, self.mocks["blocked"], self.mocks["rollout"]):
+ assert gate.call_count == 1
+ post.assert_not_called()
+
+ def test_the_ceiling_resets_after_an_hour(self) -> None:
+ with (
+ override_settings(DESKTOP_GATEWAY_MINTS_PER_HOUR=1),
+ time_machine.travel("2026-09-24T12:00:00Z", tick=False) as clock,
+ ):
+ first, _ = self._mint()
+ clock.move_to("2026-09-24T12:59:00Z")
+ within_the_hour, _ = self._mint()
+ clock.move_to("2026-09-24T13:00:01Z")
+ after_the_hour, _ = self._mint()
+ assert [first.status_code, within_the_hour.status_code, after_the_hour.status_code] == [201, 429, 201]
+
+ def test_the_ceiling_is_per_user(self) -> None:
+ other = self._create_user("[email protected]")
+ with override_settings(DESKTOP_GATEWAY_MINTS_PER_HOUR=1):
+ first, _ = self._mint()
+ other_token = OAuthAccessToken.objects.create(
+ user=other,
+ application=self.application,
+ token=f"pha_desktop_{uuid.uuid4().hex}",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="llm_gateway:read",
+ scoped_teams=[self.team.id],
+ )
+ other_client = APIClient()
+ other_client.credentials(HTTP_AUTHORIZATION=f"Bearer {other_token.token}")
+ second, _ = self._mint(other_client)
+ third, _ = self._mint()
+ assert [first.status_code, second.status_code, third.status_code] == [201, 201, 429]
+
+ def test_mint_failure_is_captured_without_code_variables(self) -> None:
+ with (
+ patch(f"{_VIEW}.capture_exception") as capture,
+ patch(f"{_VIEW}.posthoganalytics.set_capture_exception_code_variables_context") as code_vars,
+ ):
+ self._mint(go=_response(500))
+ code_vars.assert_called_once_with(False)
+ capture.assert_called_once()
+
+
+@time_machine.travel("2026-09-23T12:00:00Z", tick=False)
+class TestDesktopUsageEndpoint(_GatewayTestBase):
+ def _usage(self, limited_resources: dict | None = None):
+ with patch(
+ "ee.billing.quota_limiting.get_fresh_team_limited_resources",
+ side_effect=lambda _token: {
+ resource: (limited_resources or {}).get(resource.value, False)
+ for resource in __import__("ee.billing.quota_limiting", fromlist=["QuotaResource"]).QuotaResource
+ },
+ ):
+ return self._client().get(self._url("usage"))
+
+ def test_body_matches_the_legacy_contract_field_by_field(self) -> None:
+ self.organization.usage = {
+ "period": ["2026-09-01T00:00:00Z", "2026-10-01T00:00:00Z"],
+ "posthog_code_credits": {"usage": 1200, "todays_usage": 34, "limit": 5000},
+ "posthog_code_token_credits": {"usage": 900, "todays_usage": 0},
+ "sandbox_compute_credits": {"usage": 334.0},
+ "sandbox_compute_cpu_millicore_seconds": {"usage": 12.5},
+ }
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.POSTHOG_CODE_USAGE, "name": "PostHog Desktop usage billing"}
+ ]
+ self.organization.save()
+
+ response = self._usage()
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "product": "posthog_code",
+ "user_id": self.user.id,
+ "burst": {
+ "used_percent": 0.0,
+ "resets_in_seconds": 86400,
+ "reset_at": "2026-09-24T12:00:00Z",
+ "exceeded": False,
+ },
+ "sustained": {
+ "used_percent": 0.0,
+ "resets_in_seconds": 2592000,
+ "reset_at": "2026-10-23T12:00:00Z",
+ "exceeded": False,
+ },
+ "ai_credits": {
+ "exhausted": False,
+ "used_usd": 12.34,
+ "limit_usd": 50.0,
+ "breakdown": {
+ "token_credits": 900,
+ "compute_credits": 334,
+ # A fractional unit is not a count; legacy reports it as unknown.
+ "cpu_millicore_seconds": None,
+ "memory_mib_seconds": None,
+ },
+ },
+ "is_rate_limited": False,
+ "is_pro": False,
+ "code_usage_subscribed": True,
+ "billing_period_end": "2026-10-01T00:00:00Z",
+ }
+
+ def test_unsynced_org_reports_unknown_not_zero(self) -> None:
+ body = self._usage().json()
+ assert body["ai_credits"] == {"exhausted": False, "used_usd": None, "limit_usd": None, "breakdown": None}
+ assert body["billing_period_end"] is None
+ assert body["code_usage_subscribed"] is False
+
+ def test_exhausted_bucket_is_rate_limited(self) -> None:
+ body = self._usage({"posthog_code_credits": True}).json()
+ assert body["ai_credits"]["exhausted"] is True
+ assert body["is_rate_limited"] is True
+
+ def test_ai_credits_limit_does_not_leak_into_the_desktop_bucket(self) -> None:
+ body = self._usage({"ai_credits": True}).json()
+ assert body["ai_credits"]["exhausted"] is False
+ assert body["is_rate_limited"] is False
+
+ def test_deactivated_org_is_exhausted_and_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.save()
+ # Token callers are refused upstream of the view; a session reaches the body.
+ with patch("ee.billing.quota_limiting.get_fresh_team_limited_resources", side_effect=Exception("unused")):
+ body = self.client.get(self._url("usage")).json()
+ refused = self._client().get(self._url("usage"))
+ assert body["ai_credits"]["exhausted"] is True
+ assert body["is_rate_limited"] is True
+ assert body["code_usage_subscribed"] is False
+ assert refused.status_code == status.HTTP_403_FORBIDDEN
+ assert refused.json()["code"] == "organization_deactivated"
+
+
+class TestDesktopEndpointsRequireAuthentication(_GatewayTestBase):
+ @parameterized.expand([("mint", "post", "gateway_token"), ("usage", "get", "usage")])
+ def test_anonymous_request_is_refused(self, _name, method, path) -> None:
+ with patch(_POST) as post:
+ response = getattr(APIClient(), method)(self._url(path), {}, format="json")
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+ assert "enabled" not in response.json() and "ai_credits" not in response.json()
+ post.assert_not_called()