:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): send a limit tier with posthog code gateway tokens (#111207)
Brandond3a320f75fcd
diff --git a/products/tasks/backend/facade/desktop_gateway.py b/products/tasks/backend/facade/desktop_gateway.pyindex c5818f841db6..333100c4fb8d 100644--- a/products/tasks/backend/facade/desktop_gateway.py+++ b/products/tasks/backend/facade/desktop_gateway.py@@ -7,6 +7,7 @@ from products.tasks.backend.logic.services.desktop_gateway_token import (_team_credit_refusal as team_credit_refusal,desktop_gateway_base_url,desktop_gateway_configured,+ desktop_limit_tier,desktop_rollout_enabled,desktop_token_ttl_seconds,mint_desktop_gateway_token,@@ -22,6 +23,7 @@ __all__ = ["DesktopGatewayMintError","desktop_gateway_base_url","desktop_gateway_configured",+ "desktop_limit_tier","desktop_rollout_enabled","desktop_token_ttl_seconds","mint_desktop_gateway_token",diff --git a/products/tasks/backend/logic/services/desktop_gateway_token.py b/products/tasks/backend/logic/services/desktop_gateway_token.pyindex c62329f9eb2b..5e57b3d33dc7 100644--- a/products/tasks/backend/logic/services/desktop_gateway_token.py+++ b/products/tasks/backend/logic/services/desktop_gateway_token.py@@ -8,11 +8,13 @@ import jsonimport loggingimport functoolsfrom collections.abc import Mapping+from datetime import timedeltafrom decimal import Decimal, InvalidOperationfrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Literalfrom django.conf import settings+from django.utils import timezoneimport requestsimport posthoganalytics@@ -61,6 +63,20 @@ _MINT_TIMEOUT_SECONDS = 3PosthogCodePlan = Literal["paid", "free"]+# The gateway's per-user spend limits for a token; see AI_GATEWAY_USER_LIMITS.+LimitTier = Literal["provisional", "standard", "power", "exempt"]++# Payload {"tier": "power" | "exempt"}. A person flag: email, organization_id and team_id ride as+# person properties, so one flag can target staff by email and power users by org or team.+DESKTOP_GATEWAY_LIMIT_OVERRIDE_FLAG = "posthog-desktop-gateway-limit-override"+_OVERRIDE_TIERS: frozenset[str] = frozenset({"power", "exempt"})++DESKTOP_GATEWAY_LIMIT_TIERS = Counter(+ "posthog_desktop_gateway_limit_tiers_total",+ "PostHog Desktop gateway mints by the limit tier sent (provisional/standard/power/exempt)",+ labelnames=["tier"],+)+DESKTOP_GATEWAY_MINTS = Counter("posthog_desktop_gateway_token_mints_total","PostHog Desktop gateway token mints, by outcome (ok/rate_limited/refused/unreachable/malformed)",@@ -154,7 +170,9 @@ 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:+def desktop_rollout_enabled(+ organization: "Organization", team: "Team", distinct_id: str | None = None, email: 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:@@ -162,6 +180,8 @@ def desktop_rollout_enabled(organization: "Organization", team: "Team", distinctsettings.DESKTOP_GATEWAY_ROLLOUT_FLAG,distinct_id or organization_id,groups={"organization": organization_id, "project": str(team.id)},+ # Always sent: the stored person email is client-writable ($set).+ person_properties={"email": email or ""},group_properties={"organization": {"id": organization_id}},only_evaluate_locally=False,send_feature_flag_events=False,@@ -171,6 +191,79 @@ def desktop_rollout_enabled(organization: "Organization", team: "Team", distinctreturn False+def posthog_code_billing_synced(organization: "Organization") -> bool:+ """True once billing has synced posthog_code_credits usage and a period: the inputs quota+ limiting needs before it can limit the org (ee/billing/quota_limiting.py). Billing writes an+ empty entry for an org it does not bill, so the entry must carry usage or a limit."""+ usage = organization.usage or {}+ entry = usage.get("posthog_code_credits")+ return bool(usage.get("period")) and isinstance(entry, dict) and ("usage" in entry or "limit" in entry)+++# (org age below, minimum highest product trust score); older orgs need none. Matches the+# legacy gateway's PostHog Code account trust policy.+_TRUST_MINIMUMS: tuple[tuple[timedelta, float], ...] = ((timedelta(days=7), 7), (timedelta(days=30), 3))+++def posthog_code_trusted(organization: "Organization") -> bool:+ """Whether the org's age and best product trust score clear the minimum; a missing or+ malformed score counts as zero."""+ scores = organization.customer_trust_scores or {}+ best = max((float(v) for v in scores.values() if isinstance(v, int | float)), default=0.0)+ age = timezone.now() - organization.created_at+ for below_age, minimum in _TRUST_MINIMUMS:+ if age < below_age:+ return best >= minimum+ return True+++def _override_tier(raw: object) -> LimitTier | None:+ if isinstance(raw, str):+ try:+ raw = json.loads(raw)+ except ValueError:+ logger.warning("desktop_gateway_token: limit override payload is not JSON")+ return None+ tier = raw.get("tier") if isinstance(raw, dict) else None+ if tier in _OVERRIDE_TIERS:+ return tier+ if raw is not None:+ logger.warning("desktop_gateway_token: limit override payload has no valid tier")+ return None+++def desktop_limit_tier(+ *, organization: "Organization", team: "Team", distinct_id: str | None, email: str | None = None+) -> LimitTier:+ """The override flag's tier, else provisional until billing has synced and the org clears the+ trust minimum, else standard. A flag outage falls back to the default tier, never a looser one."""+ raw: object = None+ if distinct_id:+ # Always sent: the stored person email is client-writable ($set). Blank matches nothing.+ person_properties = {+ "organization_id": str(organization.id),+ "team_id": str(team.id),+ "email": email or "",+ }+ try:+ raw = posthoganalytics.get_feature_flag_payload(+ DESKTOP_GATEWAY_LIMIT_OVERRIDE_FLAG,+ distinct_id,+ person_properties=person_properties,+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception:+ logger.warning("desktop_gateway_token: limit override flag unavailable", exc_info=True)+ tier: LimitTier = _override_tier(raw) or (+ "standard"+ if posthog_code_billing_synced(organization) and posthog_code_trusted(organization)+ else "provisional"+ )+ DESKTOP_GATEWAY_LIMIT_TIERS.labels(tier=tier).inc()+ return tier++class DesktopGatewayMintError(Exception):def __init__(self, message: str, *, rate_limited: bool = False) -> None:super().__init__(message)@@ -206,7 +299,9 @@ 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]:+def mint_desktop_gateway_token(+ *, team_id: int, user: str, allowed_models: list[str], limit_tier: LimitTier = "standard"+) -> dict[str, Any]:"""Mint one session token; returns Go's body. Raises DesktopGatewayMintError on any refusal ortransport failure; the bearer never appears in logs or exception text."""body = {@@ -216,6 +311,7 @@ def mint_desktop_gateway_token(*, team_id: int, user: str, allowed_models: list["obo": str(team_id),"user": user,"allowed_models": allowed_models,+ "limit_tier": limit_tier,}try:response = requests.post(diff --git a/products/tasks/backend/presentation/views/desktop_access.py b/products/tasks/backend/presentation/views/desktop_access.pyindex 078cf1c1f417..49c24a1629b0 100644--- a/products/tasks/backend/presentation/views/desktop_access.py+++ b/products/tasks/backend/presentation/views/desktop_access.py@@ -38,6 +38,7 @@ from products.tasks.backend.facade.desktop_gateway import (DesktopGatewayMintError,desktop_gateway_base_url,desktop_gateway_configured,+ desktop_limit_tier,desktop_rollout_enabled,desktop_token_ttl_seconds,mint_desktop_gateway_token,@@ -239,7 +240,7 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if not desktop_gateway_configured():return _disabled("unconfigured")- if not desktop_rollout_enabled(organization, team, distinct_id):+ if not desktop_rollout_enabled(organization, team, distinct_id, user.email):return _disabled("not_rolled_out")try:@@ -281,7 +282,14 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):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)+ minted = mint_desktop_gateway_token(+ team_id=team.id,+ user=distinct_id,+ allowed_models=allowed_models,+ limit_tier=desktop_limit_tier(+ organization=organization, team=team, distinct_id=distinct_id, email=user.email+ ),+ )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.diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 07d5790de7ee..f8820a72ab2b 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -26,6 +26,7 @@ from products.tasks.backend.logic.services.desktop_gateway_token import (_cap_override,_team_credit_refusal,_valid_cap,+ desktop_limit_tier,desktop_rollout_enabled,posthog_code_plan,valid_caps,@@ -187,7 +188,7 @@ def _posthog_code_refusal(team_id: int, model: str | None, distinct_id: str | Nounpinned or paid-model run could fall back to."""team = _posthog_code_team(team_id)# The run's user, so a person-targeted flag moves cloud runs with that person's desktop sessions.- if team is None or not desktop_rollout_enabled(team.organization, team, distinct_id):+ if team is None or not desktop_rollout_enabled(team.organization, team, distinct_id, _account_email(distinct_id)):return "not_rolled_out"if posthog_code_plan(team) == "free" and not model_allowed_by_pin(FREE_TIER_MODELS, model):return "model_outside_pin"@@ -201,6 +202,25 @@ def posthog_code_allowed_models(team_id: int) -> list[str] | None:return None+def posthog_code_limit_tier(team_id: int, distinct_id: str | None) -> str | None:+ """The run user's per-user limit tier on the gateway; None when the team is gone."""+ team = _posthog_code_team(team_id)+ if team is None:+ return None+ return desktop_limit_tier(+ organization=team.organization, team=team, distinct_id=distinct_id, email=_account_email(distinct_id)+ )+++def _account_email(distinct_id: str | None) -> str | None:+ """The run user's account email; the person's stored email is client-writable."""+ if not distinct_id:+ return None+ from posthog.models import User # noqa: PLC0415++ return User.objects.filter(distinct_id=distinct_id).values_list("email", flat=True).first()++def mint_refusal(ai_product: str,*,@@ -325,6 +345,7 @@ def mint_scoped_token(team_id: int,user: str | None = None,allowed_models: list[str] | None = None,+ limit_tier: str | None = None,capture_mode: Literal["none"] | None = None,expires_in_seconds: int | None = None,) -> str | None:@@ -354,6 +375,8 @@ def mint_scoped_token(pin = allowed_models if allowed_models is not None else _PRODUCT_ALLOWED_MODELS.get(ai_product)if pin:body["allowed_models"] = pin+ if limit_tier:+ body["limit_tier"] = limit_tierif capture_mode is not None:body["capture_mode"] = capture_modelast_error: str = ""diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 54f45bee26e9..46853b8fa1fa 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@@ -14,7 +14,7 @@ from django.test import override_settingsfrom posthog.constants import AvailableFeaturefrom posthog.llm.gateway_client import GatewayNotConfiguredError-from posthog.models import Organization, Team+from posthog.models import Organization, Team, Userfrom products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGEfrom products.tasks.backend import model_catalog@@ -243,6 +243,14 @@ class TestMintScopedToken:assert set(pin) == {model for model in registry if "/" not in model} | set(SDK_IMPLICIT_MODELS)assert any("/" in model for model in registry), "the catalog no longer offers a gateway-served model"+ def test_limit_tier_is_sent_only_when_given(self, mint_settings):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ mint_scoped_token(ai_product="posthog_code", team_id=123, limit_tier="power")+ assert post.call_args.kwargs["json"]["limit_tier"] == "power"+ mint_scoped_token(ai_product="signals_scout", team_id=123)+ assert "limit_tier" not in post.call_args.kwargs["json"]+def test_non_pinned_products_send_no_allowed_models(self, mint_settings):with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:post.return_value = self._response(201, {"token": "phe_abc"})@@ -1483,8 +1491,11 @@ class TestPosthogCodeSandboxMint:) as flag,patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token"),):+ User.objects.create(email="[email protected]", distinct_id="run-user-distinct-id")ai_gateway_env_vars(team_id=team.id, origin_product="user_created", distinct_id="run-user-distinct-id")assert flag.call_args.args[1] == "run-user-distinct-id"+ # The account email, never the person's stored one.+ assert flag.call_args.kwargs["person_properties"] == {"email": "[email protected]"}@pytest.mark.django_dbdef test_off_pin_model_refuses(self):@@ -1513,8 +1524,13 @@ class TestPosthogCodeSandboxMint:) as mint,):env = ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model="@cf/zai-org/glm-5.2")+ # An org with no synced billing mints provisional.mint.assert_called_once_with(- ai_product="posthog_code", team_id=team.id, user=None, allowed_models=FREE_TIER_MODELS+ ai_product="posthog_code",+ team_id=team.id,+ user=None,+ allowed_models=FREE_TIER_MODELS,+ limit_tier="provisional",)assert env["AI_GATEWAY_PRODUCT"] == "posthog_code"assert env[utils._PIN_KEY_ENV] == FREE_TIER_PIN_KEY@@ -1531,10 +1547,43 @@ class TestPosthogCodeSandboxMint:) 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)+ mint.assert_called_once_with(ai_product="posthog_code", team_id=team.id, user=None, limit_tier="provisional")assert env["AI_GATEWAY_TOKEN"] == "phe_abc"assert utils._PIN_KEY_ENV not in env+ @pytest.mark.django_db+ def test_the_run_user_reaches_the_limit_tier(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.posthog_code_limit_tier", return_value="power"+ ) as tier,+ patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"+ ) as mint,+ ):+ ai_gateway_env_vars(team_id=team.id, origin_product="user_created", distinct_id="run-user")+ tier.assert_called_once_with(team.id, "run-user")+ assert mint.call_args.kwargs["limit_tier"] == "power"++ @pytest.mark.django_db+ def test_the_worker_tier_uses_the_account_email_not_the_person(self):+ from products.tasks.backend.temporal.process_task.ai_gateway_token import posthog_code_limit_tier++ team = self._team(paid=True)+ user = User.objects.create(email="[email protected]", distinct_id="run-user")+ with patch(+ "products.tasks.backend.temporal.process_task.ai_gateway_token.desktop_limit_tier", return_value="exempt"+ ) as tier:+ assert posthog_code_limit_tier(team.id, user.distinct_id) == "exempt"+ assert tier.call_args.kwargs["email"] == "[email protected]"+ assert tier.call_args.kwargs["distinct_id"] == "run-user"+ posthog_code_limit_tier(team.id, "nobody")+ assert tier.call_args.kwargs["email"] is None+def test_run_state_stamps_the_product_pin(self, mint_settings):env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "posthog_code"}with (diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 0b0d0da9cd4c..eeaeed464d2d 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -66,6 +66,7 @@ from products.tasks.backend.temporal.process_task.ai_gateway_token import (mint_refusal,mint_scoped_token,posthog_code_allowed_models,+ posthog_code_limit_tier,resolve_sandbox_ai_product,sandbox_product_routed,token_cap_usd,@@ -1533,6 +1534,7 @@ def ai_gateway_env_vars(free_pin = posthog_code_allowed_models(team_id)if free_pin is not None:mint_kwargs["allowed_models"] = free_pin+ mint_kwargs["limit_tier"] = posthog_code_limit_tier(team_id, distinct_id)token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id, **mint_kwargs)if token:env_vars["AI_GATEWAY_TOKEN"] = tokendiff --git a/products/tasks/backend/tests/test_desktop_gateway_token.py b/products/tasks/backend/tests/test_desktop_gateway_token.pyindex 9c5e3fd13632..b9d6e3cdd291 100644--- a/products/tasks/backend/tests/test_desktop_gateway_token.py+++ b/products/tasks/backend/tests/test_desktop_gateway_token.py@@ -21,7 +21,12 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEVfrom 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.desktop_gateway_token import (+ DESKTOP_GATEWAY_MINTS,+ desktop_limit_tier,+ posthog_code_billing_synced,+ posthog_code_trusted,+)from products.tasks.backend.logic.services.gateway_model_pin import DESKTOP_AGENT_MODELS, FREE_TIER_MODELSfrom ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState@@ -100,6 +105,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):"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),+ "tier": patch(f"{_VIEW}.desktop_limit_tier", return_value="standard"),}self.mocks = {name: patcher.start() for name, patcher in self.gates.items()}for patcher in self.gates.values():@@ -219,8 +225,13 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):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)+ organization, team, distinct_id, email = self.mocks["rollout"].call_args.args+ assert (organization.id, team.id, distinct_id, email) == (+ self.organization.id,+ self.team.id,+ self.user.distinct_id,+ self.user.email,+ )def test_blocked_desktop_access_is_refused_before_billing(self) -> None:self.mocks["access"].return_value = DesktopAccessDecision.STARTUP_PLAN@@ -288,6 +299,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):"obo": str(self.team.id),"user": self.user.distinct_id,"allowed_models": FREE_TIER_MODELS,+ "limit_tier": "standard",}assert response.json() == {"enabled": True,@@ -303,6 +315,18 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):"product_models": DESKTOP_AGENT_MODELS,}+ def test_the_limit_tier_is_chosen_for_this_user_and_sent(self) -> None:+ self.mocks["tier"].return_value = "provisional"+ response, post = self._mint()+ assert response.status_code == status.HTTP_201_CREATED+ assert post.call_args.kwargs["json"]["limit_tier"] == "provisional"+ assert self.mocks["tier"].call_args.kwargs == {+ "organization": self.organization,+ "team": self.team,+ "distinct_id": self.user.distinct_id,+ "email": self.user.email,+ }+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"}@@ -600,3 +624,119 @@ class TestDesktopEndpointsRequireAuthentication(_GatewayTestBase):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()+++_FLAG = "products.tasks.backend.logic.services.desktop_gateway_token.posthoganalytics.get_feature_flag_payload"+++class TestDesktopLimitTier(APIBaseTest):+ def _tier(+ self,+ *,+ payload: object = None,+ synced: bool = True,+ trusted: bool = True,+ distinct_id: str | None = "d1",+ email: str | None = "[email protected]",+ ):+ self.organization.usage = (+ {"period": ["2026-10-01", "2026-11-01"], "posthog_code_credits": {"usage": 0, "limit": 100}}+ if synced+ else None+ )+ self.organization.customer_trust_scores = {"posthog_code_credits": 10} if trusted else {}+ with patch(_FLAG, return_value=payload) as flag:+ tier = desktop_limit_tier(+ organization=self.organization, team=self.team, distinct_id=distinct_id, email=email+ )+ return tier, flag++ @parameterized.expand(+ [+ ("exempt", {"tier": "exempt"}, "exempt"),+ ("power", {"tier": "power"}, "power"),+ ("json string", '{"tier": "power"}', "power"),+ ("unknown tier", {"tier": "unlimited"}, "standard"),+ ("standard is not an override", {"tier": "standard"}, "standard"),+ ("not json", "{oops", "standard"),+ ("no payload", None, "standard"),+ ]+ )+ def test_override_payload(self, _name, payload, expected) -> None:+ assert self._tier(payload=payload)[0] == expected++ def test_unsynced_billing_is_provisional(self) -> None:+ assert self._tier(synced=False)[0] == "provisional"++ def test_override_beats_unsynced_billing(self) -> None:+ assert self._tier(payload={"tier": "exempt"}, synced=False)[0] == "exempt"++ def test_a_flag_outage_keeps_the_default(self) -> None:+ self.organization.usage = None+ self.organization.customer_trust_scores = {"posthog_code_credits": 10}+ with patch(_FLAG, side_effect=RuntimeError("flags down")):+ tier = desktop_limit_tier(organization=self.organization, team=self.team, distinct_id="d1")+ assert tier == "provisional"++ def test_the_flag_targets_the_person_by_email_org_and_team(self) -> None:+ _, flag = self._tier()+ assert flag.call_args.args == ("posthog-desktop-gateway-limit-override", "d1")+ assert flag.call_args.kwargs["person_properties"] == {+ "organization_id": str(self.organization.id),+ "team_id": str(self.team.id),+ "email": "[email protected]",+ }++ def test_an_unknown_email_is_blanked_so_a_stored_email_never_matches(self) -> None:+ _, flag = self._tier(email=None)+ assert flag.call_args.kwargs["person_properties"]["email"] == ""++ def test_an_untrusted_new_org_is_provisional_even_when_synced(self) -> None:+ assert self._tier(trusted=False)[0] == "provisional"++ def test_no_distinct_id_skips_the_flag(self) -> None:+ tier, flag = self._tier(payload={"tier": "exempt"}, distinct_id=None)+ assert tier == "standard"+ flag.assert_not_called()++ @parameterized.expand(+ [+ ("no usage", None, False),+ ("no period", {"posthog_code_credits": {"limit": 100}}, False),+ ("no posthog_code entry", {"period": ["a", "b"]}, False),+ (+ "empty entry billing writes for an unbilled org",+ {"period": ["a", "b"], "posthog_code_credits": {}},+ False,+ ),+ ("synced with a limit", {"period": ["a", "b"], "posthog_code_credits": {"limit": 100}}, True),+ ("synced unlimited", {"period": ["a", "b"], "posthog_code_credits": {"limit": None}}, True),+ ("synced usage only", {"period": ["a", "b"], "posthog_code_credits": {"usage": 3}}, True),+ ]+ )+ def test_billing_synced(self, _name, usage, expected) -> None:+ self.organization.usage = usage+ assert posthog_code_billing_synced(self.organization) is expected+++class TestPosthogCodeTrusted(APIBaseTest):+ @parameterized.expand(+ [+ ("new org below 7", 2, {"posthog_code_credits": 6}, False),+ ("6-day-old org needs 7", 6, {"posthog_code_credits": 6}, False),+ ("8-day-old org needs 3", 8, {"posthog_code_credits": 3}, True),+ ("29-day-old org needs 3", 29, {"posthog_code_credits": 2}, False),+ ("new org at 7", 2, {"posthog_code_credits": 7}, True),+ ("new org best score of any product", 2, {"ai_credits": 8, "posthog_code_credits": 0}, True),+ ("new org no score", 2, {}, False),+ ("new org malformed score", 2, {"posthog_code_credits": "9"}, False),+ ("week-old org below 3", 10, {"posthog_code_credits": 2}, False),+ ("week-old org at 3", 10, {"posthog_code_credits": 3}, True),+ ("25-day-old org below 3", 25, {"posthog_code_credits": 2}, False),+ ("month-old org no score", 31, {}, True),+ ]+ )+ def test_age_and_trust(self, _name, age_days, scores, expected) -> None:+ self.organization.created_at = timezone.now() - timedelta(days=age_days)+ self.organization.customer_trust_scores = scores+ assert posthog_code_trusted(self.organization) is expected