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(subscriptions): cap active AI summaries per org by plan tier (#57372)

Paul D'Ambra7670c55576a9
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index ecb5fa9dc25a..1707f3ab61f5 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -3,6 +3,7 @@ import asyncio
from typing import Any, Optional
from django.conf import settings
+from django.core.cache import cache
from django.db.models import QuerySet
from django.http import HttpRequest, JsonResponse
@@ -27,13 +28,14 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY, AvailableFeature
from posthog.event_usage import groups
+from posthog.exceptions import QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
from posthog.models import Insight
from posthog.models.integration import Integration
from posthog.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token
from posthog.permissions import PremiumFeaturePermission
from posthog.rate_limit import SubscriptionTestDeliveryThrottle
-from posthog.resource_limits import LimitKey, check_count_limit
+from posthog.resource_limits import LimitKey, check_count_limit, get_organization_limit
from posthog.security.url_validation import is_url_allowed
from posthog.slo.context import SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation
@@ -43,6 +45,32 @@ from posthog.utils import str_to_bool
from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT
+SUMMARY_QUOTA_CACHE_TTL_SECONDS = 60
+SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS = 600
+
+
+def _summary_quota_cache_key(organization_id) -> str:
+ return f"subscription:summary_quota:org:{organization_id}"
+
+
+def _summary_cap_hit_dedupe_key(organization_id) -> str:
+ return f"subscription:summary_cap_hit:org:{organization_id}"
+
+
+def _count_active_summaries(organization) -> int:
+ """Count subscriptions with summary_enabled=True (and not soft-deleted) across
+ every team in this organization. Single source of truth for both the cap-check
+ in the serializer and the `summary_quota` action endpoint."""
+ return Subscription.objects.filter(
+ team__organization_id=organization.id,
+ summary_enabled=True,
+ deleted=False,
+ ).count()
+
+
+def _invalidate_summary_quota_cache(organization_id) -> None:
+ cache.delete(_summary_quota_cache_key(organization_id))
+
@extend_schema_field({"type": "array", "items": {"type": "integer"}})
class DashboardExportInsightsField(serializers.Field):
@@ -207,8 +235,79 @@ class SubscriptionSerializer(serializers.ModelSerializer):
"AI data processing must be approved by your organization before enabling AI summaries"
)
+ # Cap gate: fire whenever the row is *becoming* an active summary
+ # (summary_enabled=True AND deleted=False) but wasn't before. This
+ # catches creates with the toggle on, off→on transitions, AND
+ # restoring a soft-deleted summary that was already summary_enabled
+ # — otherwise PATCHing `deleted=False` on a grandfathered row would
+ # bypass the cap entirely.
+ if self._is_becoming_active_summary(attrs):
+ organization = self.context["get_organization"]()
+ self._validate_summary_enabled_org_limit(organization)
+
return attrs
+ def _is_becoming_active_summary(self, attrs: dict) -> bool:
+ pre_summary_enabled = self.instance.summary_enabled if self.instance else False
+ pre_deleted = self.instance.deleted if self.instance else False
+ post_summary_enabled = attrs.get("summary_enabled", pre_summary_enabled)
+ post_deleted = attrs.get("deleted", pre_deleted)
+
+ pre_active = pre_summary_enabled and not pre_deleted
+ post_active = post_summary_enabled and not post_deleted
+ return post_active and not pre_active
+
+ def _validate_summary_enabled_org_limit(self, organization) -> None:
+ # Already-on subscriptions stay on for grandfathered orgs already over
+ # the cap; the becoming-active check in validate() ensures we only get
+ # here when the row is transitioning into the active-summary state.
+ limit = get_organization_limit(
+ organization=organization,
+ key=LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG,
+ )
+ if limit is None:
+ return
+
+ active_count = _count_active_summaries(organization)
+ if active_count >= limit:
+ self._capture_summary_cap_hit(organization, active_count, limit)
+ raise QuotaLimitExceeded(
+ f"Your plan allows up to {limit} active AI summaries. "
+ "Disable an existing summary or upgrade your plan to add more."
+ )
+
+ def _capture_summary_cap_hit(self, organization, active_count: int, limit: int) -> None:
+ # Rate-limited to one event per org per 10 minutes so a misbehaving
+ # client retrying in a loop doesn't spam the analytics stream. Within
+ # that window the user-visible 402 still fires every time.
+ dedupe_key = _summary_cap_hit_dedupe_key(organization.id)
+ if cache.get(dedupe_key):
+ return
+ cache.set(dedupe_key, True, SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS)
+
+ request = self.context.get("request")
+ distinct_id = (
+ str(request.user.distinct_id)
+ if request and getattr(request, "user", None) and getattr(request.user, "distinct_id", None)
+ else f"team_{self.context.get('team_id')}"
+ )
+ try:
+ posthoganalytics.capture(
+ distinct_id=distinct_id,
+ event="subscription_ai_summary_cap_hit",
+ properties={
+ "team_id": self.context.get("team_id"),
+ "organization_id": str(organization.id),
+ "active_count": active_count,
+ "limit": limit,
+ "is_create": self.instance is None,
+ },
+ groups={"organization": str(organization.id)},
+ )
+ except Exception:
+ # Telemetry must never poison the validation path.
+ pass
+
def _prompt_guide_feature_enabled(self) -> bool:
"""Evaluate the prompt-guide feature flag for the caller's organization.
@@ -301,6 +400,11 @@ class SubscriptionSerializer(serializers.ModelSerializer):
dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])
instance: Subscription = super().create(validated_data)
+ # Bust the org-wide active-summary count cache so the next quota
+ # fetch reflects this row, regardless of summary_enabled — over-busting
+ # is cheap and removes the need to track the prior state.
+ _invalidate_summary_quota_cache(instance.team.organization_id)
+
if dashboard_export_insight_ids:
instance.dashboard_export_insights.set(dashboard_export_insight_ids)
@@ -378,9 +482,11 @@ class SubscriptionSerializer(serializers.ModelSerializer):
},
):
instance = super().update(instance, validated_data)
+ _invalidate_summary_quota_cache(instance.team.organization_id)
return instance
instance = super().update(instance, validated_data)
+ _invalidate_summary_quota_cache(instance.team.organization_id)
if dashboard_export_insight_ids:
instance.dashboard_export_insights.set(dashboard_export_insight_ids)
@@ -519,6 +625,52 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
return queryset
+ @extend_schema(
+ request=None,
+ responses={
+ 200: OpenApiResponse(
+ description=(
+ "Org-wide AI summary quota: count of currently-active summaries and the limit "
+ "for the org's plan tier. `limit` is null when no cap is configured."
+ ),
+ response={
+ "type": "object",
+ "properties": {
+ "active_count": {"type": "integer"},
+ "limit": {"type": "integer", "nullable": True},
+ "at_limit": {"type": "boolean"},
+ },
+ "required": ["active_count", "limit", "at_limit"],
+ },
+ )
+ },
+ )
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="summary_quota",
+ required_scopes=["subscription:read"],
+ )
+ def summary_quota(self, request, **kwargs):
+ organization = self.organization
+ cache_key = _summary_quota_cache_key(organization.id)
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return Response(cached)
+
+ active_count = _count_active_summaries(organization)
+ limit = get_organization_limit(
+ organization=organization,
+ key=LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG,
+ )
+ payload = {
+ "active_count": active_count,
+ "limit": limit,
+ "at_limit": limit is not None and active_count >= limit,
+ }
+ cache.set(cache_key, payload, SUMMARY_QUOTA_CACHE_TTL_SECONDS)
+ return Response(payload)
+
@extend_schema(
request=None,
responses={202: OpenApiResponse(description="Test delivery workflow started")},
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 3daf3392136c..c091def1dff3 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -543,6 +543,276 @@ class TestSubscriptionTemporal(APILicensedTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
assert "AI summary context" in response.json()["detail"]
+ def _seed_active_summary_subscriptions(self, count: int) -> list[Subscription]:
+ # Build raw rows so we can place an org over its tier cap to exercise
+ # grandfathering paths without going through the enforced API.
+ return [
+ Subscription.objects.create(
+ team=self.team,
+ insight=self.insight,
+ target_type="email",
+ target_value=f"existing-{i}@posthog.com",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=UTC),
+ title=f"existing {i}",
+ created_by=self.user,
+ summary_enabled=True,
+ )
+ for i in range(count)
+ ]
+
+ @parameterized.expand(
+ [
+ ("create_under_limit", 5, 4, status.HTTP_201_CREATED),
+ ("create_at_limit", 5, 5, status.HTTP_402_PAYMENT_REQUIRED),
+ ("create_over_limit_grandfathered", 5, 7, status.HTTP_402_PAYMENT_REQUIRED),
+ ("create_no_limit_configured", None, 1000, status.HTTP_201_CREATED),
+ ]
+ )
+ def test_create_summary_enabled_respects_org_limit(
+ self,
+ _name: str,
+ limit: int | None,
+ existing_active: int,
+ expected_status: int,
+ ) -> None:
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(existing_active)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=limit):
+ response = self._create_subscription(summary_enabled=True)
+
+ assert response.status_code == expected_status, response.content
+ if expected_status == status.HTTP_402_PAYMENT_REQUIRED:
+ assert "active AI summaries" in response.json()["detail"]
+
+ def test_patch_transition_to_summary_enabled_blocked_at_limit(self) -> None:
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(5)
+ # The subscription being patched is currently OFF, so flipping it ON
+ # would push the org from 5 -> 6.
+ create_response = self._create_subscription(summary_enabled=False)
+ sub_id = create_response.json()["id"]
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=5):
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"summary_enabled": True},
+ )
+
+ assert patch_response.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert "active AI summaries" in patch_response.json()["detail"]
+
+ def test_patch_unrelated_field_on_already_enabled_summary_when_org_over_limit(self) -> None:
+ # Grandfathered org with 7 active when the limit is 5 must still be
+ # able to edit other fields on those rows. PATCHes that don't change
+ # summary_enabled don't re-trigger the cap check.
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ existing = self._seed_active_summary_subscriptions(7)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=5):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{existing[0].id}",
+ {"title": "renamed while over the cap"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["title"] == "renamed while over the cap"
+ assert response.json()["summary_enabled"] is True
+
+ @parameterized.expand(
+ [
+ ("under_limit", 3, 10, False),
+ ("at_limit", 5, 5, True),
+ ]
+ )
+ def test_summary_quota_endpoint(
+ self,
+ _name: str,
+ active_count: int,
+ limit: int,
+ expected_at_limit: bool,
+ ) -> None:
+ cache.clear()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(active_count)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=limit):
+ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summary_quota")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ payload = response.json()
+ assert payload["active_count"] == active_count
+ assert payload["limit"] == limit
+ assert payload["at_limit"] is expected_at_limit
+
+ def test_summary_quota_endpoint_uses_cache_and_invalidates_on_save(self) -> None:
+ # Tight integration check: hot path is the cached read; mutating a
+ # subscription via the API busts the cache so the next read reflects
+ # the new state without waiting for the TTL.
+ cache.clear()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(2)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=10):
+ first = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summary_quota")
+ assert first.status_code == status.HTTP_200_OK
+ assert first.json()["active_count"] == 2
+
+ # New row added directly in DB should NOT be visible — cache hit.
+ self._seed_active_summary_subscriptions(1)
+ second = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summary_quota")
+ assert second.json()["active_count"] == 2
+
+ # Saving via the API path busts the cache.
+ self._create_subscription(summary_enabled=True)
+ third = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summary_quota")
+ # 2 seeded + 1 direct + 1 via API = 4 active.
+ assert third.json()["active_count"] == 4
+
+ def test_cap_hit_emits_event_and_dedupes_within_window(self) -> None:
+ # Verifies the cap-hit telemetry fires with rich properties on first
+ # block and is suppressed on subsequent blocks within the dedupe
+ # window so a misbehaving client can't spam the analytics stream.
+ cache.clear()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(5)
+
+ with (
+ patch("ee.api.subscription.get_organization_limit", return_value=5),
+ patch("ee.api.subscription.posthoganalytics.capture") as mock_capture,
+ ):
+ first = self._create_subscription(summary_enabled=True)
+ second = self._create_subscription(summary_enabled=True)
+
+ assert first.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert second.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert mock_capture.call_count == 1
+ captured_kwargs = mock_capture.call_args.kwargs
+ assert captured_kwargs["event"] == "subscription_ai_summary_cap_hit"
+ properties = captured_kwargs["properties"]
+ assert properties["active_count"] == 5
+ assert properties["limit"] == 5
+ assert properties["organization_id"] == str(self.organization.id)
+ assert properties["is_create"] is True
+
+ def test_restoring_deleted_summary_enabled_subscription_re_checks_cap(self) -> None:
+ # An attacker (or a curious user) PATCHing `deleted=False` on a
+ # soft-deleted summary_enabled=True subscription must re-trigger the
+ # cap — otherwise undeleting can grow the active count past the
+ # configured limit without ever flipping summary_enabled.
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self._seed_active_summary_subscriptions(5)
+ deleted_summary = Subscription.objects.create(
+ team=self.team,
+ insight=self.insight,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=UTC),
+ title="soft-deleted",
+ created_by=self.user,
+ summary_enabled=True,
+ deleted=True,
+ )
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=5):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{deleted_summary.id}",
+ {"deleted": False},
+ )
+
+ assert response.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert "active AI summaries" in response.json()["detail"]
+
+ def test_grandfathered_toggle_off_succeeds_but_back_on_blocked(self) -> None:
+ # Toggling off frees a slot; toggling back on while still at/over the
+ # cap is rejected. Together this enforces "you can't grow past the cap".
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ existing = self._seed_active_summary_subscriptions(7)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=5):
+ off_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{existing[0].id}",
+ {"summary_enabled": False},
+ )
+ on_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{existing[0].id}",
+ {"summary_enabled": True},
+ )
+
+ assert off_response.status_code == status.HTTP_200_OK
+ assert off_response.json()["summary_enabled"] is False
+ assert on_response.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert "active AI summaries" in on_response.json()["detail"]
+
+ def test_cap_is_enforced_across_teams_in_the_same_organization(self) -> None:
+ # Documents intent: the cap is org-scoped, not team-scoped. Subscriptions
+ # spread across multiple teams in the same organization all count toward
+ # the same bucket — so a fresh team in a maxed-out org can't add a new
+ # summary even if that team has none of its own.
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+
+ team_two = Team.objects.create(organization=self.organization, name="Team two")
+ team_three = Team.objects.create(organization=self.organization, name="Team three")
+ team_three_insight = Insight.objects.create(
+ filters=Filter(data=self.insight_filter_dict).to_dict(),
+ team=team_three,
+ created_by=self.user,
+ )
+
+ def _seed_for_team(team: Team, count: int) -> None:
+ for i in range(count):
+ Subscription.objects.create(
+ team=team,
+ insight=Insight.objects.create(
+ filters=Filter(data=self.insight_filter_dict).to_dict(),
+ team=team,
+ created_by=self.user,
+ ),
+ target_type="email",
+ target_value=f"{team.id}-{i}@posthog.com",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=UTC),
+ title=f"existing {team.id}/{i}",
+ created_by=self.user,
+ summary_enabled=True,
+ )
+
+ _seed_for_team(self.team, 2)
+ _seed_for_team(team_two, 2)
+ _seed_for_team(team_three, 1)
+
+ with patch("ee.api.subscription.get_organization_limit", return_value=5):
+ response = self.client.post(
+ f"/api/projects/{team_three.id}/subscriptions",
+ {
+ "insight": team_three_insight.id,
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": "2022-01-01T00:00:00",
+ "title": "team three's sixth across-org summary",
+ "summary_enabled": True,
+ },
+ )
+
+ assert response.status_code == status.HTTP_402_PAYMENT_REQUIRED
+ assert "active AI summaries" in response.json()["detail"]
+
def test_deliver_subscription(self):
mock_client = MagicMock()
mock_client.start_workflow = AsyncMock()
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 9d1dc2e46cc8..a2799725bfb8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1104,6 +1104,10 @@ snapshots:
hash: v1.k794b7964.5d57afe52a1ebf42759db600790b9b247fcf438d12ef373de80320d970d579df.fkhtCvkkJgUkkxmzrGmXX9dTjrnH9LYj-6opPvQCEPU
components-sso-select--sso-select--light:
hash: v1.k794b7964.ae3ecf63f33e98350bb2cc9aa9b9458e0985c910f97b3251d837ee30b97a3c48.HKoN2BOvJoiBCjXKNt17mEo4yuzNnN3XmyVO9nAwgjc
+ components-subscriptions--subscription-at-ai-summary-limit--dark:
+ hash: v1.k794b7964.4b1fe224f34652580b8e6be6c6ae294bf0ee828417aed5dfd8d04505bbbdfa7a.vp-YJxXUVeUtmYuc8hwJZ6ZMbr41Wa8mey8-Sgdo5zI
+ components-subscriptions--subscription-at-ai-summary-limit--light:
+ hash: v1.k794b7964.8f8007ae1b5ab0172d712cc15f25209eae133ed35654bd5dcc0cb28cadb4ab26.RNun_WV1Ku_UFh-OOt-brcTUtr6YQGHsgAxmlCD1m_w
components-subscriptions--subscription-no-integrations--dark:
hash: v1.k794b7964.4b1fe224f34652580b8e6be6c6ae294bf0ee828417aed5dfd8d04505bbbdfa7a.jUXTpsX4PKOrM6J-AVLKCcNMgvT2g76heDlY0HxyFnA
components-subscriptions--subscription-no-integrations--light:
@@ -1168,6 +1172,22 @@ snapshots:
hash: v1.k794b7964.24519a5de47c075829e8edc4a5aa5d230bfc3d8fabd6768f1a48a942b8864b2d.LNJiDFue4r3cWY3uH-RRn4nxvpNpWMCvhrrZvj34_y8
components-tz-label--with-more-than-one--light:
hash: v1.k794b7964.eb6c920c0eed0ad217d48efd2fcc25792b567e576b92600e89a06490d7e47365.JlmFQTNBZHp82P-B2gInFlFg-we7jfSULlesHhXa00o
+ components-usage-limit-paywall--custom-cta--dark:
+ hash: v1.k794b7964.62393c23cd2e4e1bc88216c2042eccd42e2058ea9e7106f655e076f052cf19ef.Z7XEI2ZN3JkJuIVtwgDqMlyw1kXSWkxZy-eo0NayUA0
+ components-usage-limit-paywall--custom-cta--light:
+ hash: v1.k794b7964.ba5679d8dff20d80fb6356ca9cbcba6190e0d46a70e1cf7c96d3720f4fa11443.PpdOGp4cOByiBtwDh1EA5qz3524BQen_OAYocLv6-PQ
+ components-usage-limit-paywall--default--dark:
+ hash: v1.k794b7964.ef650a8b813c29a00a0c8b905ff790bd1ed14815882c060da2424a8f52d2c02f.8TUrb3poZ6Oj-4PVxOndM_gPnqhepSM4Duea5N1hMrM
+ components-usage-limit-paywall--default--light:
+ hash: v1.k794b7964.da6851466d06c723665be1790587f78c00fe64aa5f82582e661e548baa2c5e38.D35E4p3pyos72ImvkvOhsWfMYcgL0qTGKz-sbEhaACs
+ components-usage-limit-paywall--without-background--dark:
+ hash: v1.k794b7964.b277003d0b58d31fa10ca4dde9b9b13dc49194b1bc5d1c5905bd84193c73c86f.Vb48-9NlZdxCq6vf0MsJ-ZktoXpMYM-HVZBOBtXYij0
+ components-usage-limit-paywall--without-background--light:
+ hash: v1.k794b7964.3c7dd463412bcf6b2dd04c48c445a325aa4de8232dc2bd1c5d4bfffad146c73d.MepOdlOhWFyrWF42Pk3mzDTKBffyBDamtrxEHJe0i-c
+ components-usage-limit-paywall--without-current-usage--dark:
+ hash: v1.k794b7964.6330302239ac2a8e53133511d36524337e41364be2fac405730658245c8a9fcc.Hf0khRaazWBjJDR3jY_jInyXRpjbBw8R-41EOJBhqS4
+ components-usage-limit-paywall--without-current-usage--light:
+ hash: v1.k794b7964.efc336d7d7e360174bb381dd0d6c84055b1ce7f40fe8cdc4f9bc778c5cc850d4.7QnANT4hEqbE4jBHoRxZWSeZxQnXg12KhKhJfHZROog
components-usagemetriccard--long-metric-name-truncates--dark:
hash: v1.k794b7964.ed5b1bd8084cf4f186fbf1882bd9c357f300474e3b1dab2ded3ab946f4137a55.pEW7r0oAMb_bm22hvd2jfhRq-cGfLF6-sKJboFBZplU
components-usagemetriccard--long-metric-name-truncates--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 2ca6ab31ca3d..6a20a38e9d4a 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3431,6 +3431,13 @@ export const SubscriptionsListTargetType = {
Webhook: 'webhook',
} as const
+export type SubscriptionsSummaryQuotaRetrieve200 = {
+ active_count: number
+ /** @nullable */
+ limit: number | null
+ at_limit: boolean
+}
+
export type UsersListParams = {
email?: string
is_staff?: boolean
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index d92285d93a94..5d8810119d0d 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -55,6 +55,7 @@ import type {
SubscriptionDeliveryApi,
SubscriptionsDeliveriesListParams,
SubscriptionsListParams,
+ SubscriptionsSummaryQuotaRetrieve200,
UserApi,
UsersListParams,
} from './api.schemas'
@@ -1705,6 +1706,20 @@ export const subscriptionsTestDeliveryCreate = async (
})
}
+export const getSubscriptionsSummaryQuotaRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/subscriptions/summary_quota/`
+}
+
+export const subscriptionsSummaryQuotaRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SubscriptionsSummaryQuotaRetrieve200> => {
+ return apiMutator<SubscriptionsSummaryQuotaRetrieve200>(getSubscriptionsSummaryQuotaRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getUsersListUrl = (params?: UsersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a9b1876ee2ab..9a3f03c8ba27 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5659,6 +5659,9 @@ const api = {
async testDelivery(subscriptionId: SubscriptionType['id']): Promise<void> {
await new ApiRequest().subscription(subscriptionId).withAction('test-delivery').create()
},
+ async summaryQuota(): Promise<{ active_count: number; limit: number | null; at_limit: boolean }> {
+ return await new ApiRequest().subscriptions().withAction('summary_quota').get()
+ },
},
integrations: {
diff --git a/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.stories.tsx b/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.stories.tsx
new file mode 100644
index 000000000000..91512fe16711
--- /dev/null
+++ b/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.stories.tsx
@@ -0,0 +1,62 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { UsageLimitPaywall } from './UsageLimitPaywall'
+
+const meta: Meta<typeof UsageLimitPaywall> = {
+ title: 'Components/Usage Limit Paywall',
+ component: UsageLimitPaywall,
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ },
+ render: (args) => (
+ <div className="p-10 max-w-4xl mx-auto">
+ <UsageLimitPaywall {...args} />
+ </div>
+ ),
+}
+export default meta
+
+type Story = StoryObj<typeof UsageLimitPaywall>
+
+export const Default: Story = {
+ args: {
+ title: 'AI summary limit reached',
+ description: 'Disable an existing AI summary or upgrade your plan to add more.',
+ limit: 10,
+ currentUsage: 10,
+ unit: 'active AI summaries on your plan',
+ },
+}
+
+export const WithoutCurrentUsage: Story = {
+ args: {
+ title: 'Cohort limit reached',
+ description: 'You have reached the maximum number of cohorts on your current plan.',
+ limit: 50,
+ unit: 'cohorts',
+ },
+}
+
+export const WithoutBackground: Story = {
+ args: {
+ title: 'AI summary limit reached',
+ description: 'Disable an existing AI summary or upgrade your plan to add more.',
+ limit: 10,
+ currentUsage: 12,
+ unit: 'active AI summaries on your plan',
+ background: false,
+ },
+}
+
+export const CustomCta: Story = {
+ args: {
+ title: 'Recordings retention limit',
+ description: 'You can store more by upgrading your plan or trimming what you have.',
+ limit: 30,
+ currentUsage: 30,
+ unit: 'days of retention',
+ ctaLabel: 'Manage retention',
+ ctaTo: '/settings/environment-replay',
+ },
+}
diff --git a/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.tsx b/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.tsx
new file mode 100644
index 000000000000..beb6c05a6a35
--- /dev/null
+++ b/frontend/src/lib/components/PayGateMini/UsageLimitPaywall.tsx
@@ -0,0 +1,55 @@
+import clsx from 'clsx'
+
+import { IconLock } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+interface UsageLimitPaywallProps {
+ title: string
+ description?: React.ReactNode
+ limit: number
+ currentUsage?: number
+ unit?: string
+ ctaLabel?: string
+ ctaTo?: string
+ className?: string
+ background?: boolean
+}
+
+export function UsageLimitPaywall({
+ title,
+ description,
+ limit,
+ currentUsage,
+ unit = 'allowed on your plan',
+ ctaLabel = 'View plans',
+ ctaTo = urls.organizationBilling(),
+ className,
+ background = true,
+}: UsageLimitPaywallProps): JSX.Element {
+ return (
+ <div
+ className={clsx(
+ className,
+ background && 'bg-primary border border-primary',
+ 'PayGateMini rounded flex flex-col items-center p-4 text-center'
+ )}
+ >
+ <div className="flex mb-2 text-4xl text-warning">
+ <IconLock />
+ </div>
+ <h2>{title}</h2>
+ {description && <p className="max-w-140">{description}</p>}
+ <p className="p-4 border rounded border-primary bg-primary">
+ <b>{limit}</b> {unit}
+ {currentUsage !== undefined && (
+ <span className="text-secondary"> ({currentUsage} currently in use)</span>
+ )}
+ </p>
+ <LemonButton type="primary" center to={ctaTo}>
+ {ctaLabel}
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
index 962eb6c27d69..e84b7060f6cb 100644
--- a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
+++ b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx
@@ -1,7 +1,11 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { Meta, StoryObj } from '@storybook/react'
-import { useRef, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { uuid } from 'lib/utils'
import { useStorybookMocks } from '~/mocks/browser'
@@ -12,7 +16,11 @@ import { AvailableFeature, InsightShortId, Realm } from '~/types'
import { SubscriptionsModal, SubscriptionsModalProps } from './SubscriptionsModal'
-type StoryArgs = SubscriptionsModalProps & { noIntegrations?: boolean; featureAvailable?: boolean }
+type StoryArgs = SubscriptionsModalProps & {
+ noIntegrations?: boolean
+ featureAvailable?: boolean
+ aiSummaryAtLimit?: boolean
+}
const meta: Meta<StoryArgs> = {
title: 'Components/Subscriptions',
@@ -23,12 +31,29 @@ const meta: Meta<StoryArgs> = {
mockDate: '2023-01-31 12:00:00',
},
render: (args) => {
- const { noIntegrations = false, featureAvailable = true, ...props } = args
+ const { noIntegrations = false, featureAvailable = true, aiSummaryAtLimit = false, ...props } = args
const insightShortIdRef = useRef(props.insightShortId || (uuid() as InsightShortId))
const [modalOpen, setModalOpen] = useState(false)
useAvailableFeatures(featureAvailable ? [AvailableFeature.SUBSCRIPTIONS] : [])
+ useEffect(() => {
+ if (!aiSummaryAtLimit) {
+ return
+ }
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS], {
+ [FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS]: true,
+ })
+ // Reset on unmount so the flag doesn't leak into other stories
+ // rendered later in the same Storybook session.
+ return () => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS]: false,
+ })
+ }
+ }, [aiSummaryAtLimit])
+
useStorybookMocks({
get: {
'/_preflight': {
@@ -40,6 +65,14 @@ const meta: Meta<StoryArgs> = {
: { available: true, client_id: 'test-client-id' },
site_url: noIntegrations ? 'bad-value' : window.location.origin,
},
+ ...(aiSummaryAtLimit
+ ? {
+ '/api/organizations/@current/': {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: true,
+ },
+ }
+ : {}),
'/api/environments/:id/subscriptions': {
results:
insightShortIdRef.current === 'empty'
@@ -62,6 +95,9 @@ const meta: Meta<StoryArgs> = {
],
},
'/api/environments/:id/subscriptions/:subId': createMockSubscription(),
+ '/api/projects/:id/subscriptions/summary_quota': aiSummaryAtLimit
+ ? { active_count: 10, limit: 10, at_limit: true }
+ : { active_count: 0, limit: 10, at_limit: false },
'/api/projects/:id/integrations': { results: !noIntegrations ? [mockIntegration] : [] },
'/api/projects/:id/integrations/:intId/channels': { channels: mockSlackChannels },
},
@@ -123,3 +159,7 @@ export const SubscriptionsEdit: Story = {
export const SubscriptionsUnavailable: Story = {
args: { featureAvailable: false },
}
+
+export const SubscriptionAtAISummaryLimit: Story = {
+ args: { subscriptionId: 'new', aiSummaryAtLimit: true },
+}
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
index ca257c99a4fc..ef09a041d9e9 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
@@ -92,6 +92,12 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
return { ...NEW_SUBSCRIPTION }
},
},
+ summaryQuota: {
+ __default: null as { active_count: number; limit: number | null; at_limit: boolean } | null,
+ loadSummaryQuota: async () => {
+ return await api.subscriptions.summaryQuota()
+ },
+ },
})),
forms(({ props, actions }) => ({
@@ -161,6 +167,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
// this change is propagated to `subscriptions` there
subscriptionsLogic.findMounted(props)?.actions.loadSubscriptions()
actions.loadSubscriptionSuccess(updatedSub)
+ actions.loadSummaryQuota()
lemonToast.success(`Subscription saved.`)
return updatedSub
@@ -269,7 +276,16 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
},
})),
- events(({ values }) => ({
+ events(({ actions, values }) => ({
+ afterMount: () => {
+ // Load the org-wide AI summary quota once per logic mount so
+ // the paywall conditional in EditSubscription has data to react
+ // to without depending on URL navigation. urlToAction kept its
+ // own loader call in case the user navigates between :id and
+ // /new without unmounting; afterMount covers initial mount and
+ // Storybook (which doesn't navigate the route).
+ actions.loadSummaryQuota()
+ },
beforeUnmount: () => {
if (values.previewImageUrl) {
URL.revokeObjectURL(values.previewImageUrl)
diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
index 191851bddd99..a8163b15bd20 100644
--- a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
@@ -6,6 +6,7 @@ import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'
import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
import { FlaggedFeature } from 'lib/components/FlaggedFeature'
+import { UsageLimitPaywall } from 'lib/components/PayGateMini/UsageLimitPaywall'
import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'
import { usersLemonSelectOptions } from 'lib/components/UserSelectItem'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -72,7 +73,8 @@ export function EditSubscription({
})
const { meFirstMembers, membersLoading } = useValues(membersLogic)
- const { subscription, subscriptionLoading, isSubscriptionSubmitting, subscriptionChanged } = useValues(logic)
+ const { subscription, subscriptionLoading, isSubscriptionSubmitting, subscriptionChanged, summaryQuota } =
+ useValues(logic)
const { previewLoading, previewError, previewImageUrl } = useValues(logic)
const { resetSubscription, generatePreview } = useActions(logic)
const { preflight, siteUrlMisconfigured } = useValues(preflightLogic)
@@ -441,13 +443,25 @@ export function EditSubscription({
disabledReason={
!dataProcessingAccepted && !value
? 'Your organization needs to approve AI data processing before enabling AI summaries'
- : undefined
+ : summaryQuota?.at_limit && !value
+ ? `Plan limit reached (${summaryQuota.limit} active AI summaries). See details below.`
+ : undefined
}
/>
</AIConsentPopoverWrapper>
)}
</LemonField>
+ {summaryQuota?.at_limit && !subscription.summary_enabled && summaryQuota.limit !== null && (
+ <UsageLimitPaywall
+ title="AI summary limit reached"
+ description="Disable an existing AI summary or upgrade your plan to add more."
+ limit={summaryQuota.limit}
+ currentUsage={summaryQuota.active_count}
+ unit="active AI summaries on your plan"
+ />
+ )}
+
{subscription.summary_enabled && (
<FlaggedFeature flag={FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE}>
<LemonField
diff --git a/posthog/resource_limits/__init__.py b/posthog/resource_limits/__init__.py
index dcd8ad3fd588..1f8769f0c299 100644
--- a/posthog/resource_limits/__init__.py
+++ b/posthog/resource_limits/__init__.py
@@ -1,4 +1,4 @@
-from posthog.resource_limits.evaluator import check_count_limit, get_limit
+from posthog.resource_limits.evaluator import check_count_limit, get_limit, get_organization_limit
from posthog.resource_limits.registry import REGISTRY, LimitDefinition, LimitKey
__all__ = [
@@ -7,4 +7,5 @@ __all__ = [
"LimitKey",
"check_count_limit",
"get_limit",
+ "get_organization_limit",
]
diff --git a/posthog/resource_limits/evaluator.py b/posthog/resource_limits/evaluator.py
index 68006e58ca33..ae99c0b4abde 100644
--- a/posthog/resource_limits/evaluator.py
+++ b/posthog/resource_limits/evaluator.py
@@ -4,6 +4,7 @@ from posthog.event_usage import report_user_action
from posthog.resource_limits.registry import get_definition
if TYPE_CHECKING:
+ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -12,6 +13,20 @@ def get_limit(*, team: "Team", key: str) -> int | None:
return get_definition(key).default
+def get_organization_limit(*, organization: "Organization", key: str) -> int | None:
+ """Resolve a tiered limit for an organization, falling back to ``default``.
+
+ For limits with ``by_plan_tier`` set, returns the value matching the
+ organization's plan tier from ``Organization.get_plan_tier()``. For
+ limits without tier overrides, returns ``default`` unchanged.
+ """
+ definition = get_definition(key)
+ if definition.by_plan_tier is None:
+ return definition.default
+ tier = organization.get_plan_tier()
+ return definition.by_plan_tier.get(tier, definition.default)
+
+
def check_count_limit(
*,
team: "Team",
diff --git a/posthog/resource_limits/registry.py b/posthog/resource_limits/registry.py
index 15d047e3f141..e0824bc94a9a 100644
--- a/posthog/resource_limits/registry.py
+++ b/posthog/resource_limits/registry.py
@@ -1,7 +1,9 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import StrEnum
from typing import Literal
+PlanTier = Literal["free", "paid", "enterprise"]
+
class LimitKey(StrEnum):
"""Stable string identifiers for every entry in the catalog. Use these
@@ -12,22 +14,31 @@ class LimitKey(StrEnum):
MAX_ALERTS_PER_TEAM = "analytics.max_alerts_per_team"
MAX_SUBSCRIPTIONS_PER_TEAM = "analytics.max_subscriptions_per_team"
MAX_ACTIONS_PER_TEAM = "analytics.max_actions_per_team"
+ MAX_ACTIVE_AI_SUMMARIES_PER_ORG = "subscriptions.max_active_ai_summaries_per_org"
@dataclass(frozen=True)
class LimitDefinition:
"""A single entry in the resource limit catalog.
- Each entry names a per-team resource we watch. When a team is about to
+ Each entry names a resource we watch. When a team is about to
create a resource that would put them at or above ``default``, the
evaluator emits a ``resource limit hit`` event. The create itself is
not blocked.
+
+ ``by_plan_tier`` carries optional tier-keyed overrides for limits that
+ scale with billing plan. When set, callers should resolve the tier via
+ the organization helper rather than reading ``default`` directly.
+ Boost and Scale collapse to "paid" because PostHog's existing tier
+ helper conflates them; revisit if/when the helper learns finer
+ granularity.
"""
key: str
description: str
default: int | None
unit: Literal["count", "bytes", "seconds"] = "count"
+ by_plan_tier: dict[PlanTier, int] | None = field(default=None)
REGISTRY: dict[str, LimitDefinition] = {
@@ -56,6 +67,12 @@ REGISTRY: dict[str, LimitDefinition] = {
description="Saved actions in a project",
default=500,
),
+ LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG: LimitDefinition(
+ key=LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG,
+ description="Subscriptions with summary_enabled=True per organization",
+ default=10,
+ by_plan_tier={"free": 10, "paid": 20, "enterprise": 100},
+ ),
}
diff --git a/posthog/resource_limits/test/test_evaluator.py b/posthog/resource_limits/test/test_evaluator.py
index d2417936a9d5..b00b03ab4b28 100644
--- a/posthog/resource_limits/test/test_evaluator.py
+++ b/posthog/resource_limits/test/test_evaluator.py
@@ -3,7 +3,8 @@ from unittest.mock import patch
from parameterized import parameterized
-from posthog.resource_limits import LimitKey, check_count_limit, get_limit
+from posthog.constants import AvailableFeature
+from posthog.resource_limits import LimitKey, check_count_limit, get_limit, get_organization_limit
from posthog.resource_limits.registry import REGISTRY, LimitDefinition
@@ -61,6 +62,43 @@ class TestCheckCountLimit(BaseTest):
report.assert_not_called()
+class TestGetOrganizationLimit(BaseTest):
+ @parameterized.expand(
+ [
+ ("free_no_features", [], 10),
+ ("paid_with_subscriptions", [{"key": AvailableFeature.SUBSCRIPTIONS}], 20),
+ ("enterprise_with_saml", [{"key": AvailableFeature.SAML}], 100),
+ ]
+ )
+ def test_resolves_tiered_limit(
+ self,
+ _name: str,
+ available_product_features: list,
+ expected_limit: int,
+ ) -> None:
+ self.organization.available_product_features = available_product_features
+ self.organization.save()
+ assert (
+ get_organization_limit(
+ organization=self.organization,
+ key=LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG,
+ )
+ == expected_limit
+ )
+
+ def test_falls_back_to_default_when_no_tier_overrides(self) -> None:
+ # MAX_DASHBOARDS_PER_TEAM has no by_plan_tier, so any org sees the catalog default.
+ self.organization.available_product_features = [{"key": AvailableFeature.SAML}]
+ self.organization.save()
+ assert (
+ get_organization_limit(
+ organization=self.organization,
+ key=LimitKey.MAX_DASHBOARDS_PER_TEAM,
+ )
+ == 500
+ )
+
+
class TestRegistryShape:
def test_every_entry_key_matches_its_dict_key(self) -> None:
for dict_key, defn in REGISTRY.items():
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 5e211700d925..65f44b9eb5b8 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -666,6 +666,9 @@ tools:
description: >
Get a specific subscription by ID. Returns the full subscription configuration including target type and
value, schedule details, next delivery date, and associated insight or dashboard.
+ subscriptions-summary-quota-retrieve:
+ operation: subscriptions_summary_quota_retrieve
+ enabled: false
subscriptions-test-delivery-create:
operation: subscriptions_test_delivery_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b8dff73a19a1..1434a1b6c75f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40277,6 +40277,13 @@ export namespace Schemas {
Webhook: 'webhook',
} as const;
+ export type EnvironmentsSubscriptionsSummaryQuotaRetrieve200 = {
+ active_count: number;
+ /** @nullable */
+ limit: number | null;
+ at_limit: boolean;
+ };
+
export type EnvironmentsUserProductListListParams = {
/**
* Number of results to return per page.
@@ -45076,6 +45083,13 @@ export namespace Schemas {
Webhook: 'webhook',
} as const;
+ export type SubscriptionsSummaryQuotaRetrieve200 = {
+ active_count: number;
+ /** @nullable */
+ limit: number | null;
+ at_limit: boolean;
+ };
+
export type SurveysListParams = {
archived?: boolean;
/**